城镇
标识
1
2
3
患者家
Id | SERIAL_NUMBER
1 | 11
2 | 12个
2 | 13
患者记录
状态| SERIAL_NUMBER
稳定| 11
到期| 12
到期| 13
我希望根据患者记录对来自城镇的每个Id进行稳定计数和过期患者。
输出应该像
结果
ID | stableRecords | expiredRecords
1 | 1 | 0
2 | 0 | 2
3 | 0 | 0
答案 0 :(得分:0)
假设patientsHome.ID
实际上是towns.ID
的外键,您可以加入3个表,根据需要进行过滤,按城镇分组,并计算行数:
SELECT t.Id, COUNT(*) as patientCount
FROM towns t
INNER JOIN patientsHome ph
on t.Id = ph.Id
INNER JOIN patientsRecords pr
on ph.serialNumber = pr.serialNumber
WHERE pr.status in ('stable', 'expire')
GROUP BY t.Id;
如果您还想对每个城镇的状态进行分类:
SELECT t.Id, pr.status, COUNT(*) as patientCount
... FROM, WHERE same as above
GROUP BY t.Id, pr.status;
答案 1 :(得分:0)
试试这个:
SELECT t.id, pr.status,
COUNT(*) AS countByStatus
FROM patientsRecords pr
INNER JOIN patientsHome ph
ON ph.serial_number = pr.serial_number
INNER JOIN towns t
ON t.id=ph.id
WHERE pr.status IN ('stable', 'expire')
GROUP BY t.id, pr.status;
请参阅sqlfiddle:http://sqlfiddle.com/#!2/028545/4
答案 2 :(得分:0)
试试这样:
select t.id,case when tt.StableRecords is null then 0 else tt.StableRecords end
as StableRecords,case when tt.expiredRecords is null then 0 else tt.expiredRecords
end as expiredRecords from towns t left join
(select ph.id, count(case when pr.status='stable' then 1 end) as StableRecords,
count(Case when pr.status='expire' then 1 end) as expiredRecords
from patientsRecords pr inner join
patientsHome ph on ph.serial_number=pr.serial_number
group by ph.id ) as tt
on t.id=tt.id