我有一张这样的桌子:
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
...但效率不高。感谢您的任何提示。