我有如下表格:
create table rrr_br(br_id nvarchar(10), location nvarchar(10))
create table rrr_profile(profileid nvarchar(10), br_id nvarchar(10))
insert into rrr_br values('AAA', 'CHN')
insert into rrr_br values('BBB', 'CHN')
insert into rrr_br values('CCC', 'CHN')
insert into rrr_br values('DDD', 'MDR')
insert into rrr_br values('EEE', 'MDR')
insert into rrr_br values('FFF', 'MDR')
insert into rrr_profile values('111', 'AAA')
insert into rrr_profile values('222', 'BBB')
insert into rrr_profile values('222', 'FFF')
现在我需要从' rrr_br'表..."地点"明智的总数和' rrr_profile'中没有的br_id数量。表
Select location 'LOCATION',
cnt 'Total Vehicles',
cnt 'Vehicles Not Processed'
from (select location,Count(*) cnt
from rrr_br vh(nolock)
group by location ) B
感谢。
预期结果如下:
Location| Total Vehicles| Vehicles Not Processed|
-------------------------------------------------
CHN | 3 | 1 |
MDR | 3 | 2 |
答案 0 :(得分:1)
使用LEFT JOIN
确定车辆是否已处理,COUNT(*)
包含所有行,COUNT(col)
排除空值。
SELECT rrr_br.location,
COUNT(*) AS Total,
COUNT(*) - COUNT(rrr_profile.profileid) AS NotProcessed
FROM rrr_br
LEFT JOIN rrr_profile ON rrr_br.br_id = rrr_profile.br_id
GROUP BY rrr_br.location