加入2个sql选择

时间:2015-06-08 13:46:48

标签: sql select join

我有两个非常相似的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 |错误|警告

1 个答案:

答案 0 :(得分: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;

表别名也使查询更容易编写和阅读。

相关问题