我正在尝试编写一个脚本,该脚本将根据调查中使用的人口统计数据组合特定的调查结果。我已经能够编写一个脚本,将人口统计数据添加在一起以创建一个新的人口统计数据,例如 M18+ 和 F18+ = A18+,它工作得很好,但是当我试图创建一个脚本来创建一个人口统计范围,例如 A18-24 时,我遇到了一些问题无法解决。
我将两个人口统计数据加在一起的第一个脚本如下:
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
这个脚本工作正常。它将两个人口统计数据相加并插入新的数据行,为每个 Com、Survey、Wk 和 Time 创建受众总和。请参阅下面的示例数据集,其中添加 M18+ 和 F18+ 已创建名为 A18+ 的新记录
让我从一个示例数据集开始:(免责声明:实时数据库中每个人口统计数据都有很多行)
com | surveyid | demo | wk | time | audience
-------------------------
1 | LO2017 | A18+ | 1 | 300 | 4.7
1 | LO2017 | F18+ | 1 | 300 | 1.9
1 | LO2017 | M18+ | 1 | 300 | 2.8
1 | LO2017 | A25+ | 1 | 300 | 2.3
1 | LO2017 | A18+ | 2 | 100 | 3.7
1 | LO2017 | F18+ | 2 | 100 | 1.9
1 | LO2017 | M18+ | 2 | 100 | 2.8
1 | LO2017 | A25+ | 2 | 100 | 4.3
我现在需要编写的是一个创建范围的脚本。请注意上表中有 A18+ 和 A25+。请记住,在我的实时表格中,所有人口统计数据都会有多行。
在此示例中,我将使用上表。因此,我需要创建一个类似的脚本,将两个人口统计数据的受众相加,然后从另一个中减去一个以创建一个范围。例如,从 A18+ 中减去 A25+ 数据以创建一个名为 A1824 的范围。我希望这是有道理的。
在下面的脚本中,我试图创建一个名为“A1824”的范围,但我要么收到“子查询返回超过 1 行”错误,要么将错误的数据插入到临时表中,其中 AudOne 和 AudTwo 的总和为每个星期和时间都一样。
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 - AudTwo;
insert into table_survey
select temp.Com, temp.survey, temp.demo, temp.Wk, temp.Time, temp.aud
from #SurveyTemp temp
drop table #SurveyTemp
这是我需要开始工作的第二个脚本,并且花了数小时试图解决但运气不佳。如果我可以提供更多信息来帮助您帮助我,请告诉我!
编辑:我的预期结果如下所示:
com | surveyid | demo | wk | time | audience
-------------------------
1 | LO2017 | A1824 | 1 | 300 | 2.4
但是会有多个行,其中有多个“wk”和“time”条目。例如:
com | surveyid | demo | wk | time | audience
-------------------------
1 | LO2017 | A1824 | 1 | 100 | 2.4
1 | LO2017 | A1824 | 1 | 200 | 3.7
1 | LO2017 | A1824 | 2 | 100 | 2.1
1 | LO2017 | A1824 | 2 | 200 | 6.2
我将在您生成#SurveyTemp 表后开始。
我不确定是否理解您的预期结果,请查看您按演示订购的表格:
每个演示有 2 个记录。如果你想添加新记录作为这两个记录之间的一些操作的结果,你应该决定是否要按 wk 和时间分组(我认为这是正确的方法),或者不。
在您的插入命令中:
您按 分组
Com, Survey, Wk, Time
,但您正在计算所有演示记录的总体受众,(不考虑 wk 和时间):恕我直言,至少
wk
应该添加到新记录中,您应该决定如何处理时间。我建议的解决方案:GROUP BY WK AND TIME
注意:我已经为每个演示添加
wk
并time
计算sum(audience)
。如您所见,第一个记录符合您的预期结果。
没有按周和时间分组
这是结果:
注意:您不需要插入和更新,它可以在单个插入操作中完成。
检查它:dbfiddle here