簡體   English   中英

SQL 查詢同一標識符的其他狀態的狀態計數

[英]SQL Query to get count of status by other status for the same identifier

我有一個表格,其中包含顯示流程步驟的記錄:

    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

但是這個查詢沒有返回我需要的結果。

關於如何實現預期結果的任何建議?

我認為這可以滿足您的要求:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM