2015-06-08 60 views
1

我有兩個非常相似的SQL語句加入2 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 |錯誤|警告

+0

將差異從WHERE子句移到COUNT中的CASE中。 – jarlh

+0

與論壇網站不同,我們不使用「謝謝」或「任何幫助表示讚賞」,或在[so]上簽名。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be - 刪除 - 從帖子)。順便說一句,這是「預先感謝」,而不是「感謝先進」。 –

回答

7

使用條件彙總:

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; 

表的別名也讓查詢更容易編寫和閱讀。

+0

非常感謝你,這工作像一個魅力... – Allen

+0

我有一個後續問題,我也需要總結測試的總數,但這隻能從dbo.test中選擇,我使用的查詢只是從dbo.test中選擇instrumentuniqueid,count(instrumentuniqueid),其中runid = 20962 group by instrumentuniqueid,但我不知道如何加入到另一個複雜的查詢 – Allen

+0

@Allen ...我懷疑'count(distinct t.id)'會做你想做的事情,如果沒有,你應該問它是另一個問題,帶有樣本數據和期望的結果。 –