如何编写实现Excel SUMIFS功能的SQL查询

时间:2013-06-25 10:30:26

标签: sql excel sumifs

我有一张这样的表:

Date        Sales   Department Store
02/01/2012   4.09    Toys       A
03/01/2012   5.90    Toys       A
02/01/2012   6.64    Toys       B
03/01/2012   4.71    Toys       B
02/01/2012   16.72   Toys       C
03/01/2012   1.37    Toys       C
02/01/2012   13.22   Movies     A
03/01/2012   18.06   Movies     A
02/01/2012   5.97    Movies     B
03/01/2012   16.71   Movies     B
02/01/2012   15.38   Movies     C
03/01/2012   19.75   Movies     C

想要一个这样的表,只考虑商店A和B:

Date        Toys    Movies
02/01/2012   10.73   19.19 
03/01/2012   10.61   34.77 

这里我们将在EXCEL中使用SUMIFS函数:

=SUMIFS(Value;Date;$H4;Department;I$3;Store;"<>C")

我们可以在SQL中写什么?

考虑到这是一个简短的例子,数据库表有超过30个部门和更多的日期。我正在使用脚本

SELECT DISTINCT Date,
ISNULL(MAX(CASE WHEN Department = 'Toys'  AND Store = 'A' THEN Sales END),0) +
ISNULL(MAX(CASE WHEN Department = 'Toys'  AND Store = 'B' THEN Sales END),0) [Toys],
ISNULL(MAX(CASE WHEN Department = 'Movies'  AND Store = 'A' THEN Sales END),0) +
ISNULL(MAX(CASE WHEN Department = 'Movies'  AND Store = 'B' THEN Sales END),0) [Movies]
FROM Table$
GROUP BY Date
ORDER BY Date

......但效率不高。感谢您的任何提示。

1 个答案:

答案 0 :(得分:2)

您的查询没问题,但可以稍微改进一下:

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;

这会移除distinct group by,这对于store是不必要的。它将where上的条件移动到ISNULL()子句,因为它适用于所有行。并且,它会在else 0声明中包含case来删除0 - 因此部门中没有销售的商店将返回NULL而不是{{1}}