我有一个这样的表:
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
…但是效率不高。感谢您的提示。
您的查询还可以,但可以进行一些改进:
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。
distinct
group by
store
where
ISNULL()
else 0
case
0
NULL