我有一张名为industry的表。有6个领域。架构如下。
在这种情况下,我需要执行自定义聚合。数据库中有22个区域。需要进行两次自定义聚合:
接下来是我尝试的整体框架。我假设创建一个新表是最简单的方法来实现这一点。底部是预期结果的一个非常简短的例子。
create table industry2
(
year char(4),
qtr char(2),
area char(6),
industry char(3),
ownership char(2),
employment numeric(8,0)
);
INSERT INTO Industry2
(year, qtr, area, industry, ownership, employment)
SELECT year, qtr, area, (select sum (employment) from dbo.industry where area
= '01' or area = '02' and so on):
2017 01 01 123000 1 456
2017 01 02 123000 1 101
2017 01 03 123000 1 103
2017 01 01 134000 1 6
2017 01 02 134000 1 7
2017 01 03 134000 1 12
2017 01 09 134000 1 1
2017 01 01 144000 1 14
2017 01 20 134000 1 7
2017 01 21 134000 1 8
预期结果
2017 01 00 123000 1 660
2017 01 00 134000 1 26
2017 01 00 144000 1 14
2017 01 99 134000 1 15
答案 0 :(得分:2)
您可以使用GROUP BY
声明定义自定义CASE WHEN
子句:
select [year],
[qtr],
case when [area] in('20','21') then '99' when [area] between 1 and 17 then '00' end as [area],
[industry],
[ownership],
sum([employment]) as [employment_sum]
from industry2
group by
[year],
[qtr],
case when [area] in('20','21') then '99' when [area] between 1 and 17 then '00' end,
[industry],
[ownership]
结果: