SQL:按日期范围对SUM值进行分组,并按日期显示在多个列中

时间:2015-06-03 21:31:47

标签: sql

我有一张SQL表,显示每人的收费金额和相关日期。我希望每月创建每个人的费用打印件。我有以下代码,它会显示每个人一个月的数据,但我想把它放在一个报告中,而不必为每个月的日期范围重新运行。有没有办法一次性提取这些数据?基本上我想要显示的列:

姓氏1月2月3月Etc

姓名amt amt amt

以下是我将4月份数据作为示例的代码。您会看到日期代码为YYYYMMDD。此代码一次完美地运行一个月。

select pm.last_name, SUM(amt) as Total_Charge from charges c
inner join provider_mstr pm ON c.rendering_id = pm.provider_id
where begin_date_of_service >= '20150401' and begin_date_of_service <= '20150431'
group by pm.last_name

3 个答案:

答案 0 :(得分:1)

将SUM(amt)更改为Total_Charge为每个句点

SUM(CASE WHEN begin_date_of_service BETWEEN '20150401' AND '20150430' THEN amt ELSE 0 END) AS April_Amt

SUM(CASE WHEN begin_date_of_service BETWEEN '20150301' AND '20150331' THEN amt ELSE 0 END) AS March_Amt

并更新WHERE子句以包含pull的所有日期范围。

答案 1 :(得分:1)

通用解决方案使用SUM over CASE:

select pm.last_name, 
  SUM(case when begin_date_of_service >= '20150101' and begin_date_of_service  < '20150201' then amt else 0 end) as Total_Charge_Jan,
  SUM(case when begin_date_of_service >= '20150201' and begin_date_of_service  < '20150301' then amt else 0 end) as Total_Charge_Feb,
  SUM(case when begin_date_of_service >= '20150301' and begin_date_of_service  < '20150401' then amt else 0 end) as Total_Charge_Mar,
...
from charges c
inner join provider_mstr pm ON c.rendering_id = pm.provider_id
where begin_date_of_service >= '20150101' and begin_date_of_service  < '20160101'
group by pm.last_name

根据您的DBMS,您可能具有PIVOT功能或类似功能......

答案 2 :(得分:0)

产品中的条件将评估为1或0,因此您可以使用以下方法进行选择性求和:

select 
   pm.last_name, 
   SUM(amt * (begin_date_of_service >= '20150401' and begin_date_of_service <= '20150431')) AS 'april', 
   SUM(amt * (begin_date_of_service >= '20150501' and begin_date_of_service <= '20150530')) AS 'may'
   ...
from charges c
inner join provider_mstr pm ON c.rendering_id = pm.provider_id
group by pm.last_name