Reputation: 143
I have a table named industry. There are 6 fields. The schema is given below.
In this case, am needing to perform custom aggregations. There are 22 areas in the database. Two custom aggregations need to be made:
Next is my attempt at an overall framework for this. I am assuming that creating a new table is the simplest way to accopmlish this. At the bottom is a very short example of the intended result.
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
Intended result
2017 01 00 123000 1 660
2017 01 00 134000 1 26
2017 01 00 144000 1 14
2017 01 99 134000 1 15
Upvotes: 1
Views: 83
Reputation: 12415
You can define your custom GROUP BY
clause with a CASE WHEN
statement:
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]
Result:
Upvotes: 2