0

我的sql架构是这样的:sqlfiddle

我想显示 TransactionID、DoctorID、PatientID 和 TotalMedicine(从每笔交易的 MedicineID 数量获得),其中 PatientID 的最后 3 位数字是 4 的倍数。按 DoctorID 升序对数据进行排序,然后将 TotalMedicine 计数为最大, 医生 ID 上的最小和平均值。

我试过这个

SELECT th.TransactionID,
       th.DoctorID,
       th.PatientID,
       COUNT(td.MedicineID) AS TotalMedicine
FROM   TransactionHeader th
       JOIN TransactionDetail td
         ON th.TransactionID = td.TransactionID
WHERE  CAST(RIGHT(th.PatientID, 3) AS INT) % 4 = 0
GROUP  BY th.TransactionID,
          th.DoctorID,
          th.PatientID
ORDER  BY th.DoctorID ASC
COMPUTE max(COUNT(td.MedicineID)), 
        min(COUNT(td.MedicineID)), 
        avg(COUNT(td.MedicineID)) BY th.DoctorID 

但它没有选择 PatientID 的最后 3 位数字,即 4 的倍数。

4

2 回答 2

2

假设您无法更改架构以提供tableHeader数据varchar类型或char(5),您需要考虑列末尾的空格。

RTRIM将满足您的需求。

SELECT th.TransactionID,
       th.DoctorID,
       th.PatientID,
       COUNT(td.MedicineID) AS TotalMedicine
FROM   TransactionHeader th
       JOIN TransactionDetail td
         ON th.TransactionID = td.TransactionID
WHERE  CAST(RIGHT(RTRIM(th.PatientID), 3) AS INT) % 4 = 0
GROUP  BY th.TransactionID,
          th.DoctorID,
          th.PatientID
ORDER  BY th.DoctorID ASC
于 2013-05-27T17:44:41.160 回答
0

添加Where Cast(Substring(PatientId, Len(PatientId) - 2, 3) as Integer) % 4 = 0

Select TransactionID, DoctorID, PatientID, 
    Sum() TotalMedicine 
From TransactionHeader th
   JOIN TransactionDetail td
     ON th.TransactionID = td.TransactionID
Where Cast(Substring(PatientId, Len(PatientId) - 2, 3) as Integer) % 4 = 0
GROUP BY th.TransactionID,
      th.DoctorID,th.PatientID
于 2013-05-27T17:43:55.300 回答