SQL查询以同一标识符的其他状态获取状态计数

时间:2020-04-09 12:16:14

标签: sql snowflake-cloud-data-platform

我有一个表,其中包含记录,这些记录显示了流程的步骤:

    Status      | ModelID
-------------------------
    Set Remote  | 1
    Train       | 1
    Trained     | 1
    Enabled     | 1
    Set Local   | 2
    Train       | 2
    Trained     | 2
    Enabled     | 2
    Set Upload  | 3
    Train       | 3
    Trained     | 3
    Set Remote  | 4
    Train       | 4
    Trained     | 4
    Enabled     | 4

我想获得以下结果

     Status      | CountTrained | CountEnabled
-------------------------------------------------
     Set Remote  | 2            | 2
     Set Local   | 1            | 1
     Set Upload  | 1            | 0

我尝试了以下查询

    select 
       sum(case when status = 'Set Local' then 1 else 0 end),
       sum(case when status = 'Set Remote' then 1 else 0 end),
       sum(case when status = 'Set Upload' then 1 else 0 end)
    from TABLE
    inner join (select 
                   distinct ModelId,
                   status  as ModelStatus
                from TABLE
                where (status = 'Trained' or status = 'Enabled')) as Model
    on Model.ModelId = TABLE.ModelId

但是此查询不会返回我需要的结果。

关于如何实现预期结果的任何建议?

1 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求

select modelid,
       max(case when status like 'Set %' then status end) as status,
       sum(case when status = 'Trained' then 1 else 0 end) as trained,
       sum(case when status = 'Enabled' then 1 else 0 end) as enabled
from t
group by modelid;
相关问题