create table #SurveyTemp
(
Com nchar(6),
Survey nvarchar(50),
Demo nchar(50),
Wk int,
Time int,
Aud decimal(18,8)
);
insert into #SurveyTemp (Com, Survey, Demo, Wk, Time, Aud)
select Com, Survey, 'A18+', Wk, Time, sum(Aud)
from table_survey
where survey = 'LO2017'
and
demograph like 'F18+'
or
surveyid = 'LO2017'
and
demograph like 'M18+'
group by Com, survey, Wk, Time:
insert into table_survey
select temp.Com, temp.Survey, temp.Demo, temp.Wk, temp.Time, temp.Aud
from #SurveyTemp temp
drop table #SurveyTemp
What iI need to write now is a script that creates a range. Notice how in the table above there is a A18+ and a A25+. Please bear in mind that in my live table there will be MULTIPLE rows for all demographs.
In this example, iI will be using the above table. So, iI need to create a similar script that will sum the audience for two demographs and then subtract one from the other to create a range. For example, subtract the A25+ data from A18+ to create a range called A1824. I hope that makes sense.
In the script below, iI am trying to create a range called 'A1824' but iI am either getting a "subquery returned more than 1 row" error OR it is inserting the wrong data into the temp table where the sum in AudOne and AudTwo is the SAME for every single Wk and Time.
create table #SurveyTemp
(
Com nchar(6),
Survey nvarchar(50),
Demo nchar(50),
Wk int,
Time int,
Aud decimal(18,8),
AudOne decimal(18,8),
AudTwo decimal(18,8)
);
insert into #SurveyTemp (Com, Survey, Demo, Wk, TimeBlock, Aud, AudOne, AudTwo)
(
select Com, Survey, 'A1824', Wk, Time, 0.0,
(select sum(aud) from table_survey where demo = 'A18+'),
(select sum(aud) from table_survey where demo = 'A25+')
from table_survey
where surveyid = 'LO2017'
group by Com, survey, Wk, Time,
)
update #SurveyTemp
set Aud = AudOne - AudTwoAudTwo;
insert into table_survey
select temp.Com, temp.survey, temp.demo, temp.Wk, temp.Time, temp.aud
from #SurveyTemp temp
drop table #SurveyTemp