sql查询来聚集结果

dnph8jn4  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(340)

一个站点有多个pod,每个pod都有一个状态。数据如下表所示:

Store   POD Status  
A001    S101    OK  
A001    S102    OK  
A001    S103    OK  
A002    S201    OK  
A002    S202    Critical  
A002    S203    OK  
A003    S301    OK  
A003    S302    OK  
A003    S303    Critical  
A004    S401    Warning  
A004    S402    OK  
A004    S403    OK  
A005    S501    OK  
A005    S502    OK  
A005    S503    OK  
A006    S601    OK  
A006    S602    OK  
A006    S603    Critical  
A007    S701    OK  
A007    S702    OK  
A007    S703    OK

计算站点状态,以便如果站点中的任何一个pod具有严重状态,则站点应报告严重,否则如果站点中的任何一个pod具有警告,则if应报告警告,

Expected Output  
A001 OK  
A002 Critical  
A003 Critical  
A004 Warning  
A005 OK  
A006 Critical  
A007 OK

为了得到预期的输出,sql查询应该是什么?

qmb5sa22

qmb5sa221#

SELECT
  store,
  ELT(
    MAX(CASE status WHEN 'OK'       THEN 1
                    WHEN 'Warning'  THEN 2
                    WHEN 'Critical' THEN 3
                                    ELSE 4 END),
    'OK',
    'Warning',
    'Critical',
    'Unknown'
  )
    AS final_status
FROM
  yourTable
GROUP BY
  store
wtzytmuj

wtzytmuj2#

你可以用 ELT 以及 conditional aggregation :

SELECT Store, ELT(MAX(CASE WHEN Status='OK' THEN 1
                       WHEN status='Warning' THEN 2
                       WHEN status='Critical' THEN 3 END)
            , 'OK', 'Warning', 'Critical') AS output
FROM tab
GROUP BY Store;

dbfiddle演示

dgtucam1

dgtucam13#

也可以使用相关方法:

select Store, (select t1.Status
               from table t1
               where t1.Store = t.Store
               order by (case when t1.Status = 'Critical' 
                              then 1  
                              when t1.Status = 'Warning' 
                              then 2
                              when t1.Status = 'OK' 
                              then 3
                         end)
                limit 1 
               ) as Status  
from table t
group by Store;

相关问题