1

这是我的数据库架构:

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 本身的新手,我不知道如何解决这个问题。我尝试了一些子选择(比如在我的小提琴中),但它们没有按预期工作。我想这是因为我必须加入子选择,但是如何?我也想知道如何做到这一点的最佳方法..

一些帮助?

4

2 回答 2

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)
于 2013-02-19T08:45:28.023 回答
1

您不需要联合多个查询。您可以使用 case 语句:

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

于 2013-02-19T08:48:10.393 回答