MS SQL Server 2005 GROUP BY和SUM

时间:2010-09-29 16:03:14

标签: sql sql-server-2005 mysql

嘿所有,我正在尝试创建一个报告,以显示每个HRCode花了多少钱。到目前为止,这是我的SQL查询:

 SELECT *
 FROM   tblWO as WO, 
        tblWOD as WOD, 
        tblWA as WA 
 WHERE WOD.OrderID = WO.ID 
 AND WA.HRCode  = WO.AdministratorCode 
 AND WO.OrderDate BETWEEN '2010-01-01' AND '2010-08-31' 
 AND Approved = '1' 
 ORDER BY WO.OrderDate

我试图找出一种方法,将所有相同的HRCode混合在一起,然后将SUM()混合在一起......但是我的大脑今天不工作,所以我需要一些帮助:o)

以下是数据库数据的样子:

ID      Total   OrderDate               Approved    HRCode    AdministratorCode    OrderID
3272      25.00   2010-01-04 10:48:57.617 1           RN        RN                   3272
4621      25.00   2010-02-04 11:15:01.600 1           RN        RN                   4621
4899      50.00   2010-02-04 11:55:01.630 1           02        02                   4899
4905      15.00   2010-05-04 11:55:01.190 1           NR        NR                   4905
5001      50.00   2010-06-04 04:11:55.295 1           RN        RN                   5001

任何帮助都会很棒!谢谢!

解决

 SELECT SUM(Total) as Total, AdministratorCode 
 FROM   tblWO as WO, 
        tblWOD as WOD
 WHERE WOD.OrderID = WO.ID 
 AND WO.OrderDate BETWEEN '2010-01-01' AND '2010-08-31' 
 AND Approved = '1' 
 ORDER BY WO.AdministratorCode

大卫

1 个答案:

答案 0 :(得分:2)

从select语句中删除OrderDate和ID列:

 SELECT SUM(Total) as Total, HRCode
 FROM   tblWO as WO,  
        tblWOD as WOD,  
        tblWA as WA  
 WHERE WOD.OrderID = WO.ID  
 AND WA.HRCode  = WO.AdministratorCode  
 AND WO.OrderDate BETWEEN '2010-01-01' AND '2010-08-31'  
 AND Approved = '1'  
 GROUP BY HRCode