我有两个非常相似的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
Run Code Online (Sandbox Code Playgroud)
第一个产生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;
Run Code Online (Sandbox Code Playgroud)
表别名也使查询更容易编写和读取.
归档时间: |
|
查看次数: |
43 次 |
最近记录: |