我需要提交报告以获取神经科医生的一些医疗数据。以下查询按月汇总总计和平均值。如何将其更改为按周拉取总计和平均值?
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);
答案 0 :(得分:3)
只需在WEEK
功能中使用MONTH
代替DATENAME
,并按其分组。
此外,查询的可读格式更像是......
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));