2016-01-03 84 views
3

我做了一個數據庫,將所有頭痛和偏頭痛跟蹤數據輸入到數據庫中。我正在拉一些查詢,顯示一年中不同頭痛嚴重程度的計數。我有一個查詢可以在一個月內解決所有令人頭疼的問題,另一個查詢則會在某種嚴重程度下令人頭疼,而最後一個問題則會讓某些程度的問題變得令人頭疼。我在數據庫中使用了兩列:HeadacheDate和Severity。我想做一個查詢,將有以下幾列作爲輸出:SQL Union在不同列中

Month, Count of All Headaches, Count of Headaches under 6 Severity, 
Count of Headaches Over 5 Severity 

我做了一個聯合查詢需要3個查詢和給我的數據我想,但我只是想不通如何做一個查詢,將移動數據,給我我想要的列格式。

這裏是我的聯合查詢:

SELECT 
    DateName(month, DateAdd(month, MONTH(HeadacheDate), -1)) AS 
HeadacheMonth, 
    COUNT(Severity) as SeverityCount 
FROM 
    Headaches 
WHERE 
    Severity > 0 AND YEAR(HeadacheDate) = 2013 
GROUP BY 
    MONTH(HeadacheDate) 

UNION 

SELECT 
    DateName(month, DateAdd(month, MONTH(HeadacheDate), -1)) AS HeadacheMonth, 
    COUNT(Severity) as SeverityCount 
FROM 
    Headaches 
WHERE 
    Severity > 0 AND Severity < 6 AND YEAR(HeadacheDate) = 2013 
GROUP BY 
    MONTH(HeadacheDate) 

UNION 

SELECT 
    DateName(month, DateAdd(month, MONTH(HeadacheDate), -1)) AS HeadacheMonth, 
    COUNT(Severity) as SeverityCount 
FROM 
    Headaches 
WHERE 
    Severity > 5 AND YEAR(HeadacheDate) = 2013 
GROUP BY 
    MONTH(HeadacheDate); 

這返回的結果是這樣的:

April 3 
April 11 
April 14 
August 5 
August 10 
August 15 
December 2 
December 11 
December 13 
July 5 
July 6 
July 11 
June 4 
June 10 
June 14 
March 1 
March 2 
March 3 
May 5 
May 8 
May 13 
November 1 
November 13 
November 14 
October 4 
October 9 
October 13 
September 4 
September 10 
September 14 

我想是這樣的:

Month, Count of All Headaches, Count of Headaches under 6 Severity, Count of Headaches Over 5 Severity 

January, 20, 15, 5 
February, 18, 13, 5 

等。

我還想包括其中一個計數字段可能爲零的月份。

回答

4

可以使用條件分組:

SELECT 
    [HeadacheMonth]  = DATENAME(month, DateAdd(month , MONTH(HeadacheDate), -1)) 
,[SeverityCountTotal] = COUNT(CASE WHEN Severity > 0 THEN 1 END) 
,[SeverityCount_1_5] = COUNT(CASE WHEN Severity > 0 
            AND Severity < 6 THEN 1 END) 
,[SeverityCount_6] = COUNT(CASE WHEN Severity > 5 THEN 1 END) 
FROM Headaches 
WHERE YEAR(HeadacheDate) = 2013 
GROUP BY MONTH(HeadacheDate); 

YEAR(HeadacheDate) = 2013不是可優化搜索,所以如果在該列的查詢優化索引出口將跳過it.You可以考慮使用:

HeadacheDate >= '2013-01-01T00:00:00' AND HeadacheDate < '2014-01-01T00:00:00' 
+1

什麼我在尋找。週二看到新的神經科醫生,所以我想準備一些報告 – David

0
SELECT Month 
     ,COUNT(Severity) AS ALL 
     ,SUM(CASE WHEN Severity<6 THEN 1 ELSE 0 END) AS SevUn6 
     ,SUM(CASE WHEN Severity>5 THEN 1 ELSE 0 END) AS SevOv5 

FROM <table> 
GROUP BY Month 
+0

如果你解釋你的代碼會更好。 –