我的 sql 架构是这样的:sqlfiddle
我想显示TransactionID,DoctorID,PatientID和TotalMedicine(从每笔交易的MedicineID数量中获得),其中PatientID的最后3位数字是4的倍数。按医生ID递增数据排序,然后计算TotalMedicine是Doctor 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的倍数。
答案 0 :(得分: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
答案 1 :(得分: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