SQL查询按周获取总计

时间:2016-07-05 00:32:37

标签: sql sql-server

我需要提交报告以获取神经科医生的一些医疗数据。以下查询按月汇总总计和平均值。如何将其更改为按周拉取总计和平均值?

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);

1 个答案:

答案 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));