在单个查询中使用多个Count

时间:2017-08-17 10:06:49

标签: sql sql-server

我在下面有一个查询,我想要返回关键&的总数。警告一天的警报,但我遇到的问题是,当我在天数范围内进行警报时,它会添加指定日期的严重警报

SELECT alertDate as "Alert Date",
    (SELECT COUNT(alertType) FROM alerts WHERE alertDate BETWEEN '2016/02/15' AND '2016/02/16' AND UPPER(alertType)='CRITICAL') as Critical,
    (SELECT COUNT(alertType) FROM alerts WHERE alertDate BETWEEN '2016/02/15' AND '2016/02/16' AND UPPER(alertType)='WARNING') as Warning
FROM alerts
where alertDate BETWEEN '2016/02/15' AND '2016/02/16'
GROUP BY alertDate;

尝试了上面的代码,但显然我无法添加" group by"子查询中的子句,我认为是问题,请帮助我如何解决这个问题......

3 个答案:

答案 0 :(得分:2)

你可以使用sum(case):

SELECT alertDate as "Alert Date",
    sum(case when UPPER(alertType)='CRITICAL' then 1 end) as Critical,
    sum(case when UPPER(alertType)='WARNING' then 1 end) as Warning
FROM alerts
where alertDate BETWEEN '2016/02/15' AND '2016/02/16'
GROUP BY alertDate;

答案 1 :(得分:2)

您希望条件聚合 - case进入聚合函数。我会把它写成:

SELECT alertDate as AlertDate,
       SUM(CASE WHEN UPPER(alertType) = 'CRITICAL' THEN 1 ELSE 0 END) as Critical,
       SUM(CASE WHEN UPPER(alertType) = 'WARNING' THEN 1 ELSE 0 END) as WARNING
FROM alerts a
WHERE alertDate BETWEEN '2016-02-15' AND '2016-02-16'
GROUP BY alertDate;

如果您使用的是MySQL,可以将其缩短为:

SELECT alertDate as AlertDate,
       SUM(UPPER(alertType) = 'CRITICAL') as Critical,
       SUM(UPPER(alertType) = 'WARNING') as Warning
FROM alerts a
WHERE alertDate BETWEEN '2016-02-15' AND '2016-02-16'
GROUP BY alertDate;

请注意其他一些变化:

  • 不需要任何子选择。
  • 我从AlertDate删除了空格。我不喜欢需要转义的列别名。
  • 我将/替换为日期文字中的- - 连字符与ISO 8601兼容。

答案 2 :(得分:0)

您应该使用像

这样的条件计数
SUM( case when alertDate BETWEEN '2016/02/15' AND '2016/02/16' 
     AND UPPER(alertType)='CRITICAL' then 1 else 0 end) as Critical,