簡體   English   中英

加入2個SQL選擇

[英]Joining 2 sql selects

我有兩個非常相似的sql語句

select instrumentuniqueid, count(levelid) as errors
   from dbo.testevent
   join dbo.test 
   on dbo.test.id = dbo.testevent.testid where dbo.test.runid = 20962 and dbo.testevent.levelid = 1
   group by instrumentuniqueid


select instrumentuniqueid, count(levelid) as warnings
   from dbo.testevent 
   join dbo.test
   on dbo.test.id = dbo.testevent.testid where runid = 20962 and levelid = 2
   group by instrumentuniqueid

第一個生成Instrumentuniqueid列(匯總)和計數。第二個生成具有不同計數值的匯總Instrumentuniqueid列。

如何將它們連接在一起,以便最終表如下所示:

Instrumentuniqueid | 錯誤| 警告事項

使用條件聚合:

select instrumentuniqueid,
       sum(case when te.levelid = 1 then 1 else 0 end) as errors,
       sum(case when te.levelid = 2 then 1 else 0 end) as warnings
   from dbo.testevent te join
        dbo.test t
        on t.id = t2.testid
where t.runid = 20962 
group by instrumentuniqueid;

表別名還使查詢更易於編寫和閱讀。

暫無
暫無

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

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