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

时间:2013-06-30 07:36:35

标签: sql database subquery

我有这样的架构

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

我希望显示PatientID,PatientName,Initial(从前两个字符中获得的患者名称,大写格式),PatientBirthDate和TransactionCount(从患者完成的考试次数中得出,并添加“交易”一词“最后)。

结果应该是这样的:

result picture

我试过了:

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

但它无效,有效的应该像照片中那样..

1 个答案:

答案 0 :(得分:0)

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

注意到内联派生表'trans'的连接 [您也可以使用CTE(公用表格表达式)执行此操作