我必须对表运行查询以获取每个特定字段值的总和。
rechargedate originid
------------------------
2015-02-02 3
2015-02-02 3
2015-02-02 1
2015-02-02 1
2015-02-02 3
2015-02-02 2
2015-02-01 2
2015-02-01 3
2015-02-01 1
2015-02-01 1
2015-02-01 2
查询结果应该是:
rechargedate orig1 orig2 orig3
-------------------------------------
2015-02-02 2 1 3
2015-02-01 2 2 1
如何使用MS SQL 2008实现这一目标?
答案 0 :(得分:4)
使用PIVOT
。查看this以了解PIVIOT
SQL SERVER.
SELECT rechargedate,
[1] AS orig1,
[2] AS orig2,
[3] AS orig3
FROM #TEST
PIVOT(COUNT(originid) FOR originid IN([1],[2],[3])) AS Piv
ORDER BY rechargedate DESC
答案 1 :(得分:1)
您可以使用条件聚合:
CREATE TABLE #temp(
RechargeDate DATE,
OriginID INT
)
INSERT INTO #temp VALUES
('2015-02-02', 3),('2015-02-02', 3),('2015-02-02', 1),
('2015-02-02', 1),('2015-02-02', 3),('2015-02-02', 2),
('2015-02-01', 2),('2015-02-01', 3),('2015-02-01', 1),
('2015-02-01', 1),('2015-02-01', 2);
SELECT
RechargeDate,
orig1 = SUM(CASE WHEN OriginID = 1 THEN 1 ELSE 0 END),
orig2 = SUM(CASE WHEN OriginID = 2 THEN 1 ELSE 0 END),
orig3 = SUM(CASE WHEN OriginID = 3 THEN 1 ELSE 0 END)
FROM #temp
GROUP BY RechargeDate
ORDER BY RechargeDate DESC
DROP TABLE #temp
<强> RESULT 强>
RechargeDate orig1 orig2 orig3
------------ ----------- ----------- -----------
2015-02-02 2 1 3
2015-02-01 2 2 1
答案 2 :(得分:1)
最简单的方法是使用CASE语句创建所需的列,然后进行求和,例如,
SELECT rechargedate,
SUM(CASE WHEN originid = 1 THEN 1 ELSE 0 END) AS orig1,
SUM(CASE WHEN originid = 2 THEN 1 ELSE 0 END) AS orig2,
SUM(CASE WHEN originid = 3 THEN 1 ELSE 0 END) AS orig3
FROM {your_table}
GROUP BY rechargedate
ORDER BY rechargedate DESC