SQL Server:按日期显示列状态

时间:2013-02-19 08:31:41

标签: sql sql-server

这是我的数据库架构:

http://sqlfiddle.com/#!3/bbaea/3

唯一重要的列是CreationTime(作为时间戳)和Result

Result目前可以是0,1,2或3

我的结果应该是什么样的:

Year, Month, Day | Entries with Result 0 | With 1 | With 2 | ..

我是SQL Server本身的新手,我不知道如何解决这个问题。我尝试了一些子选择(比如我的小提琴),但它们没有按预期工作。我想这是因为我必须加入子选择,但是如何?另外,我想知道如何做到这一点的最好方法..

一些帮助?

2 个答案:

答案 0 :(得分:1)

你可以试试这个

SELECT YEAR(CreationTime) AS y, MONTH(CreationTime) AS m, DAY(CreationTime) AS d,
       COUNT(CASE WHEN Result = 0 THEN 1 END) AS WITH0,
       COUNT(CASE WHEN Result = 1 THEN 1 END) AS WITH1,
       COUNT(CASE WHEN Result = 2 THEN 1 END) AS WITH2          
FROM History
GROUP BY YEAR(CreationTime), MONTH(CreationTime), DAY(CreationTime)

答案 1 :(得分:1)

您无需合并多个查询。您可以使用案例陈述:

SELECT
    DAY(CreationTime) AS d, MONTH(CreationTime) AS m, YEAR(CreationTime) AS y
    ,count(CASE WHEN RESULT = 0 THEN 1 ELSE NULL END) AS R0
    ,count(CASE WHEN RESULT = 1 THEN 1 ELSE NULL END) AS R1
    ,count(CASE WHEN RESULT = 2 THEN 1 ELSE NULL END) AS R2
FROM History
GROUP BY DAY(CreationTime), MONTH(CreationTime), YEAR(CreationTime)


SELECT * FROM History;

回答SQL Fiddle