0
SELECT WK_NBR,region_cd,plant_cd, POS_GAP_1DAY 
  FROM(SELECT wk_nbr,region_cd,plant_cd, 
       round((CASE WHEN SUM(gap_1day)>0 THEN SUM(gap_1day) ELSE 0 END     ),2) AS POS_GAP_1DAY
       FROM
         table a
       group by wk_nbr,region_cd,plant_cd)

In the above query the problem I am facing is POS_GAP_1DAY should sum up only the positive numbers in the column but the above query will not give the right answer since I check SUM(gap_1day)>0.

The problem is I need to group by only wk_nbr,region_cd,plant_cd.

Please suggest

2 Answers 2

3

Try change

round((CASE WHEN SUM(gap_1day)>0 THEN SUM(gap_1day) ELSE 0 END     ),2) AS POS_GAP_1DAY

to

ROUND(SUM(CASE WHEN SIGN(gap_1day) > 0 THEN gap_1day ELSE 0 END), 2) AS POS_GAP_1DAY
1
  • @Mani You're welcome. Glad it helped :D. And as Davide absolutely correctly commented it seems that your outer select is redundant. Therefore if you don't do anything else with the query get rid of it.
    – peterm
    May 13, 2013 at 8:26
2

done on the spot, so I don't know if it works, but...

 SELECT wk_nbr,region_cd,plant_cd, 
        round(SUM(CASE WHEN GAP_1DAY>0 then GAP_1DAY else 0 end),2) AS POS_GAP_1DAY
   FROM
     table a
   group by wk_nbr,region_cd,plant_cd

doesn't do what you want?

2
  • :yes it does :( I am new to SQL. Thank you so much
    – MKN
    May 13, 2013 at 8:18
  • 2
    just a quick note.. the outer select is redundant in your specific case
    – Davide
    May 13, 2013 at 8:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.