如何在sql server中按不同的日期对列组进行求和

时间:2014-04-22 14:57:04

标签: sql-server

我一直在努力创建一份总结报告,该报告将汇总本周的总数并按日期对其进行分组。请问我做错了什么

SELECT 
 SUM(Numb1) AS [ Registration], 
 SUM(Numb2) AS [RENEWAL], 
 SUM(Penalty) AS PENALTY, 
 SUM(MTR), 
 SUM(numb3) AS PH,
 SUM(Insurance) AS INSURANCE, 
 SUM(nub4) AS [data received], 
 SUM(Numb1)+ SUM(Numb2)+ SUM(Penalty)+ SUM(MTR), SUM(numb3) + SUM(Insurance)+ SUM(nub4)  AS [TOTAL SUM]
FROM dbo.Vehicle_Transactions
GROUP BY transaction_date

1 个答案:

答案 0 :(得分:1)

您可能希望按周分组,而不是按天分组。我还添加了一年,以使查询每年都有效(否则某些行将变得模糊不清,例如2013年和2014年的条目):

SELECT 
 DATEPART(wk,transaction_date) Week,
 DATEPART(yy,transaction_date) Year, --to make sure it'll work any year
 MIN(transaction_date),
 SUM(Numb1) AS [ Registration], 
 SUM(Numb2) AS [RENEWAL], 
 SUM(Penalty) AS PENALTY, 
 SUM(MTR), 
 SUM(numb3) AS PH,
 SUM(Insurance) AS INSURANCE, 
 SUM(nub4) AS [data received], 
 SUM(Numb1)+ SUM(Numb2)+ SUM(Penalty)+ SUM(MTR), 
 SUM(numb3) + SUM(Insurance)+ SUM(nub4)  AS [TOTAL SUM]
FROM dbo.Vehicle_Transactions
GROUP BY DATEPART(WK,transaction_date), DATEPART(yy,transaction_date)