SQL查询 - 值的组和SUM

时间:2015-08-07 20:30:03

标签: sql sql-server

我有以下数据库结构:

ID |付款(十进制)| PaymentDate(DateTime)| PaymentStatus(INT)

我目前能够按年份和日期对所有付款进行分组,并使用以下查询获取所有付款状态的总额;

Select 
YEAR = YEAR(DueDate),
MONTH = MONTH(DueDate),
MMM = UPPER(left(DATENAME(MONTH,DueDate),3)),
Totals = sum(Payment)
from 
PaymentSchedules
Where DueDate IS NOT NULL
Group by 
YEAR(DueDate),
MONTH(DueDate),
DATENAME(Month,DueDate)
Order By
YEAR,
MONTH

这给了我迄今为止如此好的结果。

enter image description here

我希望能够做的是为每个部分中的分组添加总计。因此,例如,如果每笔付款可能是付费(1)或未付款(2)或逾期(3)我不仅要获得付款/未付/逾期的数量,而且我还希望获得未付款项的总价值/付费项目/每年/每月组合的逾期项目。

2 个答案:

答案 0 :(得分:4)

您只需添加SUMCASE语句,仅在检测到正确状态时对付款进行总结,如下所示:

Select YEAR = YEAR(DueDate),
       MONTH = MONTH(DueDate),
       MMM = UPPER(left(DATENAME(MONTH,DueDate),3)),
       TotalPaid = sum(case when PaymentStatus = 1 then Payment else 0 end),
       TotalUnpaid = sum(case when PaymentStatus = 2 then Payment else 0 end),
       TotalOverdue = sum(case when PaymentStatus = 3 then Payment else 0 end),
       Totals = sum(Payment)
from PaymentSchedules
Where DueDate IS NOT NULL
Group by YEAR(DueDate),
         MONTH(DueDate),
         DATENAME(Month,DueDate)
Order By YEAR,
         MONTH

答案 1 :(得分:1)

由于只有3个类别,我建议直接使用CASE语句。

Select 
YEAR = YEAR(DueDate),
MONTH = MONTH(DueDate),
MMM = UPPER(left(DATENAME(MONTH,DueDate),3)),
Paid_sum = sum(CASE When PaymentStatus = 1 THEN Payment ELSE 0 END),
Unpaid_sum = sum(CASE When PaymentStatus = 2 THEN Payment ELSE 0 END),
Overdue_sum = sum(CASE When PaymentStatus = 3 THEN Payment ELSE 0 END),
Totals = sum(Payment)
from 
PaymentSchedules
Where DueDate IS NOT NULL
Group by 
YEAR(DueDate),
MONTH(DueDate),
DATENAME(Month,DueDate)
Order By
YEAR,
MONTH