2013-05-27 80 views
0

SQL模式是這樣的:sqlfiddleSQL:如何選擇最後3位數乘以4的列?

我想展示的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 

但因此未選擇最後3位數是4乘以PatientID的..

+1

'PA001'的最後3個字符爲'CHAR(10)'將是三個空格。無論如何,你爲什麼需要'PA'前綴?你不能只使用一個整數標識列嗎?對那些id部分可以被4整除的患者還有什麼意義? –

回答

2

假設你可以將您的架構更改爲tableHeader a varchar數據類型或char(5),則需要考慮en上的空格d列。

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 
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 
+1

看看他發佈的數據模式。 – DougM

+0

Thx,錯過了! –