2017-10-10 182 views
1

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

任何人都知道如何在單獨的字段下對每個計數進行排序?

+0

如果你想在一個記錄的結果,使用@ P.Salmon的回答,如果你希望他們在多條記錄,你可以用我的。 – Lamar

回答

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' 
+0

謝謝你的回答。這是關於我所追求的。 :-) – CaPsLoCkEr

0

首先,您需要在所有聯合查詢中使用相同的列名稱。第二,如果你希望所有的名字都是同一個名字,那麼你應該使用「UNION ALL」,以防萬一結果有重複記錄。

在你情況下,你可以這樣做:

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)) 
+0

謝謝拉馬爾,你的回答給了我更多的見解。 – CaPsLoCkEr