结合多个选择查询问题

时间:2017-10-10 08:28:02

标签: mysql select union

MySql查询问题:

作为sql的新手,我有以下问题。 我不得不将4个查询合并为一个用于报告软件。代码正在运行,但结果不是我想要的。

尝试使用UNION语句,显示计数但所有排序均在1' count(*)'领域。

我希望每个查询中都有4个字段(总报警,已确认总数,15分钟内确认总数,15分钟后确认总数)

到目前为止,这是我的代码:

select
  count(*) 'Total alarms'
 FROM  alarminfo
 where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0'))

union 

select
 count(ack_time) 'Total Acknowledged'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0')

 )

union 

select
   count(*) 'Total acknowledged within 15min'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0') AND
    (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)<60*15))

union 

select
   count(*) 'Total acknowledged after 15min'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0') AND
    (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)>60*15))

任何人都知道如何在单独的字段下对每个计数进行排序?

2 个答案:

答案 0 :(得分:1)

我认为你需要条件聚合。例如

select
  count(*) 'Total alarms',
  sum(case when ack_time is not null then 1 else 0 end) as 'total acknowledged',
  sum(case when (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)<60*15) then 1 else 0 end) as 'Total acknowledged within 15min',
  sum(case when (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)>60*15) then 1 else 0 end) as 'Total acknowledged after 15min'
 FROM  alarminfo
 where
 alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0'

答案 1 :(得分:0)

首先,您需要在所有联合查询中使用相同的列名。

其次,如果你想要所有人都是同一个名字,那么你应该使用&#34; UNION ALL&#34;如果结果有重复的记录。

在你的情况下,你可以这样做:

select
  count(*) AS 'count', 'Total alarms' As 'label' 
 FROM  alarminfo
 where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0'))

union 

select
 count(ack_time) AS 'count', 'Total Acknowledged' As 'label'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0')

 )

union 

select
   count(*) AS 'count', 'Total acknowledged within 15min' AS 'label'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0') AND
    (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)<60*15))

union 

select
   count(*) AS 'count',  'Total acknowledged after 15min' AS 'label'
 FROM  alarminfo
  where
 ((alarminfo.set_time>='2017-09-01 00:00:00.0' AND alarminfo.set_time<'2017-09-15 23:59:59.0') AND
    (TIMESTAMPDIFF(SECOND,alarminfo.set_time ,alarminfo.ack_time)>60*15))