我无法弄清楚如何旋转表格。我需要一个看起来像这样的输出:
Month Age_Group 90%-100% 51%-89% 26%-50% <25%
Jun-13 Early Childhood (3–5) 1 1 0 0
Jun-13 Elementary (6–10) 3 11 16 13
Jun-13 Middle School (11–13) 3 3 5 14
Jun-13 Teens (14–18) 6 7 6 10
Jun-13 Older Youth (19-21) 1 0 1 2
如果有一个 Null 值需要更改为 0,则当表旋转时。我一直在查看此处的帖子,我似乎无法围绕语法来创建 Pivot。
这是表格:
CREATE TABLE Budget_Utilization (
Month/YEAR varchar(7) ,
Child_Count int,
Budget_Utilization varchar(12),
Age_Group varchar (20) )
INSERT INTO [GW_PPP].[dbo].[WSP_services_Counts] VALUES
('Jun-13', 1, '90% and Above', 'Early Childhood (ages 3–5)'),
('Jun-13', 3, '90% and Above', 'Elementary (6–10)'),
('Jun-13', 3, '90% and Above', 'Middle School/Pre-Teen (11–13)'),
('Jun-13', 1, '90% and Above', 'Older Youth (19-21)'),
('Jun-13', 6, '90% and Above', 'Teens (14–18)'),
('Jun-13', 1, '51%-89%', 'Early Childhood (ages 3–5)'),
('Jun-13', 11, '51%-89%', 'Elementary (6–10)'),
('Jun-13', 3, '51%-89%', 'Middle School/Pre-Teen (11–13)'),
('Jun-13', 7, '51%-89%', 'Teens (14–18)'),
('Jun-13', 16, '26%-50%', 'Elementary (6–10)'),
('Jun-13', 5, '26%-50%', 'Middle School/Pre-Teen (11–13)'),
('Jun-13', 1, '26%-50%', 'Older Youth (19-21)'),
('Jun-13', 6, '26%-50%', 'Teens (14–18)'),
('Jun-13', 13, '<25%', 'Elementary (6–10)'),
('Jun-13', 14, '<25%', 'Middle School/Pre-Teen (11–13)'),
('Jun-13', 2, '<25%', 'Older Youth (19-21)'),
('Jun-13', 10, '<25%', 'Teens (14–18)')
select [Month/YEAR],
[Age_Group],
coalesce([90% and Above], 0) [90% and Above],
coalesce([51%-89%], 0) [51%-89%],
coalesce([26%-50%], 0) [26%-50%],
coalesce([<25%], 0) [<25%]
from
(
select [Month/YEAR], Child_Count, Budget_Utilization,
[Age_Group]
from [GW_PPP].[dbo].[WSP_services_Counts]
) d
pivot
(
sum(Child_Count)
for [GW_PPP].[dbo].[WSP_services_Counts] in ([90% and Above],
[51%-89%],
[26%-50%],
[<25%])
) piv