简体   繁体   中英

SQL : count foreign key in another table

i have a schema like this

http://sqlfiddle.com/#!3/690e8

i want to show PatientID, PatientName, Initial (obtained from the first 2 characters PatientName with uppercase format), PatientBirthDate, and TransactionCount (derived from the number of exam that done by the patient and added the word 'Transaction (s)' at the end).

the result should be something like this :

result picture

i have tried :

select mp.PatientID,mp.PatientName,(upper(left(mp.PatientName,2))) [initial],mp.PatientBirthDate,trans.result
from MsPatient mp,
(select COUNT(th.PatientID) as result 
from TransactionHeader th group by th.PatientID) as trans

but it was not valid,the valid one should be like in the pics..

select 
    mp.PatientID, 
    mp.PatientName, 
    upper(left(mp.PatientName, 2)) as [initial],
    mp.PatientBirthDate,
    cast(trans.result as varchar(50)) + ' Transaction(s)' as [NumberOfTransactions]
from 
    MsPatient mp
    join (select PatientID, COUNT(PatientID) as result 
          from TransactionHeader group by PatientID) trans on trans.PatientId = mp.PatientId

Note the join to the inline derived table 'trans' [You could also perform this with a CTE (Common Table Expression)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM