用于聚合结果的SQL查询

时间:2018-05-23 17:36:56

标签: mysql sql function

单个站点有多个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有警告则应报告警告

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

什么是SQL查询才能获得预期的输出?

3 个答案:

答案 0 :(得分:3)

您可以使用ELTconditional 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 Demo

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您还可以使用关联方法:

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;