How to write a SQL query implementing Excel SUMIFS function

后端 未结 1 1815
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 04:38

I have a table like this:

Date        Sales   Department Store
02/01/2012   4.09    Toys       A
03/01/2012   5.90    Toys       A
02/01/2012   6.64    Toys          


        
1条回答
  •  囚心锁ツ
    2021-01-07 05:23

    Your query is ok, but it can be improved a bit:

    SELEC Date,
          MAX(CASE WHEN Department = 'Toys' THEN Sales else 0 END) as [Toys],
          MAX(CASE WHEN Department = 'Movies' THEN Sales else 0 END) as [Movies]
    FROM Table$
    WHERE store in ('A', 'B')
    GROUP BY Date
    ORDER BY Date;
    

    This removes the distinct, which is unnecessary with a group by. It moves the condition on store to the where clause, because it applies to all the rows. And, it removes the ISNULL() by including else 0 in the case statement -- so stores with no sales in the department will return a 0 instead of NULL.

    0 讨论(0)
提交回复
热议问题