简体   繁体   English

SQL:计算另一个表中的外键

[英]SQL : count foreign key in another table

i have a schema like this 我有这样的架构

http://sqlfiddle.com/#!3/690e8 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). 我想显示PatientID,PatientName,Initial(从前两个字符的患者名以大写格式获取),PatientBirthDate和TransactionCount(从患者进行的检查次数中得出,并在“结束)。

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) 注意连接到内联派生表'trans' [您也可以使用CTE(公用表表达式)执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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