查询1:
SELECT DISTINCT sysnam,COUNT(*) AS High FROM tablename
WHERE Label00002 = '1.High' AND Item_grade = 'NON-COMPLIANT'
GROUP BY sysnam
输出:
SYSNAME,高
A,12
B,13
查询2:
SELECT DISTINCT sysnam,count(*) AS Medium FROM tablename
WHERE Label00002 = '2.Medium' AND Item_grade = 'NON-COMPLIANT'
GROUP BY sysnam
输出:SYSNAME,Medium
A,10
B,11
如何将上述查询合并为一个,并希望看到输出如下
输出:
SYSNAME,高,中
A,12,10
B,13,11
答案 0 :(得分:1)
使用条件聚合:
select sysnam,
sum(case when Label00002 = '1.High' then 1 else 0 end) as high,
sum(case when Label00002 = '2.Medium' then 1 else 0 end) as medium
from tablename
where Item_grade = 'NON-COMPLIANT'
group by sysnam;
注意:当您拥有select distinct
时,使用group by
几乎绝对不正确。
答案 1 :(得分:0)
您可以在基于相同的sysnam
的subselect上使用连接select distinct t1.sysnam,count(t1.*) as High, t2.Medium
from tablename t1
left join (
select distinct sysnam,count(*) as Medium from tablename
where Label00002 = '2.Medium' and Item_grade = 'NON-COMPLIANT'
group by sysnam
) t2 on t2.sysnam = t1.sysnam
where t1.Label00002 = '1.High'
and t1.Item_grade = 'NON-COMPLIANT'
group by sysnam
答案 2 :(得分:0)
将查询放入两个CTE并加入结果
delete_admin()