简体   繁体   中英

SQL Query to get Totals By Week

I need to pull a report to get some medical data for a neurologist. The following query pulls totals and averages by month. How can I change it to pull totals and averages by week?

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

Simply use WEEK instead of MONTH in the DATENAME function and also group by it.

Also a much more readable format of the query would be something like...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM