2016-07-05 135 views
1

我需要獲取一份報告以獲取神經科醫生的一些醫療數據。以下查詢按月份計算總計和平均值。我怎樣才能改變它以按周計算總計和平均值?SQL查詢按周獲取總計數

SELECT 
    [Month] = DATENAME(MONTH, DATEADD(MONTH, MONTH(HeadacheDate), -1)), 
    [Total] = COUNT(CASE 
    WHEN Severity > 0 THEN 1 
    END), 
    [Light] = COUNT(CASE 
    WHEN Severity > 0 AND 
     Severity < 4 THEN 1 
    END), 
    [Moderate] = COUNT(CASE 
    WHEN Severity > 3 AND 
     Severity < 7 THEN 1 
    END), 
    [Severe] = COUNT(CASE 
    WHEN Severity > 6 THEN 1 
    END), 
    [DHE or ER] = COUNT(CASE 
    WHEN Medication LIKE '%dhe%' THEN 1 
    END) 
FROM HeadacheData 
WHERE YEAR(HeadacheDate) = 2016 
GROUP BY MONTH(HeadacheDate); 

回答

3

DATENAME功能,並且還通過組它只需使用WEEK代替MONTH

而且查詢的更易讀的格式會是這樣的......

SELECT 
    [Week]  = DATENAME(WEEK, DATEADD(MONTH, MONTH(HeadacheDate), -1)) 
    ,[Total]  = COUNT(CASE WHEN Severity > 0 THEN 1 END) 
    ,[Light]  = COUNT(CASE WHEN Severity > 0 AND Severity < 4 THEN 1 END) 
    ,[Moderate] = COUNT(CASE WHEN Severity > 3 AND Severity < 7 THEN 1 END) 
    ,[Severe] = COUNT(CASE WHEN Severity > 6 THEN 1 END) 
    ,[DHE or ER] = COUNT(CASE WHEN Medication LIKE '%dhe%' THEN 1 END) 
FROM HeadacheData 
WHERE YEAR(HeadacheDate) = 2016 
GROUP BY DATENAME(WEEK, DATEADD(MONTH, MONTH(HeadacheDate), -1));