我建立了一个数据库,将我所有的头痛和偏头痛追踪数据输入。我提出了一些问题,这些查询显示了某一年内每月头痛严重程度不同的情况。我有一个问题,每个月都会头疼,另一个在一定严重程度下会头痛,最后一个会在一定程度上头疼。 I' m在数据库中使用了两列:HeadacheDate和Severity。我想做一个将以下列作为输出的查询:
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
等等。
我还想包括其中一个计数字段为零的月份。
答案 0 :(得分: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
不是SARGable,因此如果索引退出该列,查询优化器将跳过它。您可以考虑使用:
HeadacheDate >= '2013-01-01T00:00:00' AND HeadacheDate < '2014-01-01T00:00:00'
答案 1 :(得分: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