mssql查询在其他字段中总和一个字段

时间:2017-05-17 08:44:55

标签: sql sql-server

我需要实现这样的目标:

SELECT AttendDetails.Date,AttendDetails.AttendId, NameCode,PhoneNo,Patients.
[Next of Kin] as NextOfKin,Company,
ConsultFee,LabFee, XraFee as XrayFee, ECGFee,
AdmitFee,SUM(PresFee) AS TotalPresFee,MedFee,TheaterFee,ScanFee
FROM AttendDetails
LEFT JOIN Patients on AttendDetails.OPDNo = Patients.OPDNo
LEFT JOIN [Company list] on [Company list].AcNum = AttendDetails.GLOffset
LEFT JOIN ConsultDetails on  AttendDetails.AttendId = 
ConsultDetails.AttendId 
LEFT JOIN LaboratoryDetails on AttendDetails.AttendId = 
LaboratoryDetails.AttendId
LEFT JOIN XrayDetails on AttendDetails.AttendId = XrayDetails.AttendId
LEFT JOIN ECGDetails on AttendDetails.AttendId = ECGDetails.AttendId
LEFT JOIN AdmitDetails on AttendDetails.AttendId = AdmitDetails.AttendId
LEFT JOIN PrescripDetails on AttendDetails.AttendId = 
PrescripDetails.AttendId
LEFT JOIN Medicals on AttendDetails.AttendId = Medicals.AttendId
LEFT JOIN TheaterDetails on AttendDetails.AttendId = TheaterDetails.AttendId
LEFT JOIN ScanDetails on AttendDetails.AttendId = ScanDetails.AttendId
WHERE AttendDetails.GLOffset = $P{company}  
AND AttendDetails.Date BETWEEN $P{startDate}  AND $P{endDate}
GROUP BY <something>

其中一个字段是SUM值。但我似乎没有得到group by子句。或者我做错了吗?

1 个答案:

答案 0 :(得分:0)

在聚合查询期间,所有字段都必须是GROUP BY子句的一部分或受聚合函数的影响。在这种情况下,由于您只汇总了一列,因此您的分组必须是所有剩余字段:

GROUP BY
    AttendDetails.Date,
    AttendDetails.AttendId, 
    NameCode,
    PhoneNo,
    Patients.[Next of Kin],
    Company,
    ConsultFee,
    LabFee, 
    XraFee, 
    ECGFee,
    AdmitFee,
    MedFee,
    TheaterFee,
    ScanFee