在SQL中,为变量的所有选项创建具有最新小计的年度汇总表

时间:2019-06-21 17:27:14

标签: sql reporting-services

我有一个这样的数据集:

FILE_NUMBER, DATE_RECEIVED, FILE_TYPE

FILE_TYPE有大约10个选项。我希望生成一个汇总表,该表显示过去四年(包括今年)中的每一年:

YEAR, TOTAL_RECEIVED_TO_DATE, FILE_TYPE_1_TOTAL, FILE_TYPE_2_TOTAL, ....
2016, 3000, 126, 234, ....
2017, 3200, 123, 242, ....
2018, 3100, 234, 267, ....

我尝试了几个派生表,但没有成功。

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select year(DATE_RECEIVED), count(*) as total,
       sum(case when FILE_TYPE = 1 then 1 else 0 end) as file_type_1,
       sum(case when FILE_TYPE = 2 then 1 else 0 end) as file_type_2,
       . . .,
       sum(case when FILE_TYPE = 10 then 1 else 0 end) as file_type_10
from x
group by year(DATE_RECEIVED)