2015-06-08 62 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)'会做你想做的事情,如果没有,你应该问它是另一个问题,带有样本数据和期望的结果。 –