SQL DB2 - sum up sales based on condition

Mustapha George :

I want to express the following in SQL DB2. I want to add up value of sales based on one of two conditions. I think I need a CASE statement, but not sure. Let me know if pseudo code is clear..

SELECT Total_Service_Starts, Total_Service_Stops            

If ServiceFile.SERVICE_START > 20200101
   Then Total_Service_Starts  = SUM(ServiceFile.Rate * ServiceFile.Units)   

If ServiceFile.SERVICE_STOP > 20200101
   Then Total_Service_Stops  = SUM (ServiceFile.Rate * ServiceFile.Units)

thank you!

jmarkmurphy :

You are right, case is what you want. Try it this way:

select
  sum(case when ServiceFile.SERVICE_START > 20200101
              then (ServiceFile.Rate * ServiceFile.Units)   
           else 0 end) as "TotalServiceStarts",
  sum(case when ServiceFile.SERVICE_STOP > 20200101
              then (ServiceFile.Rate * ServiceFile.Units)
           else 0 end) as "TotalServiceStops"
from ServiceFile
where service_start > 20200101
   or service_stop > 20200101;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368464&siteId=1