Question

I have three tables towns , patientsHome,patientsRecords

towns

Id
1
2
3

patientsHome

Id | serial_number
1 | 11
2 | 12
2 | 13

patientsRecords

status | serial_number
stable | 11
expire | 12
expire | 13

I want to count stable and expire patients from patients records against each Id from towns.

output should be like

Result

Id| stableRecords |expiredRecords
1| 1 | 0
2| 0 | 2
3| 0 | 0

Was it helpful?

Solution

Try like this :

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

OTHER TIPS

Assuming patientsHome.ID is in fact a foreign key to towns.ID, you can join the 3 tables, filter as appropriate, group by Town, and count the rows:

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;

If you also want to classify the status per town:

SELECT t.Id, pr.status, COUNT(*) as patientCount
... FROM, WHERE same as above
GROUP BY t.Id, pr.status;

Try this:

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;

See the sqlfiddle: http://sqlfiddle.com/#!2/028545/4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top