问题描述
我正在尝试创建列来显示每一行的百分比,其中分母是给定年份中所有行的总和。
目前我创建的查询如下所示:
SELECT
pend,ReportingPeriod,Area,SubsCategoryId,gender,age_group,Ethnicity,AllInTx_Count,NewTx_Count
FROM
(
SELECT
p.pend,p.Area,AllInTx AS AllInTx_Count,NewTx AS NewTx_Count
FROM
(
SELECT
pend,CONVERT(char(4),DATEPART(yy,pend) - 1) + '/' + RIGHT(CONVERT(char(4),pend)),2) AS ReportingPeriod,'White' AS Ethnicity,SUM(Eth_White_NewTx) AS NewTx,SUM(Eth_White_AllInTx) AS AllInTx
FROM
dbo.ViewIt_Main
GROUP BY
pend,age_group
UNION ALL
SELECT
pend,'Mixed/Multiple ethnic group' AS Ethnicity,SUM(Eth_Mixed_NewTx) AS NewTx,SUM(Eth_Mixed_AllInTx) AS AllInTx
FROM
dbo.ViewIt_Main AS ViewIt_Main_5
GROUP BY
pend,'Asian/Asian British' AS Ethnicity,SUM(Eth_Asian_NewTx) AS NewTx,SUM(Eth_Asian_AllInTx) AS AllInTx
FROM
dbo.ViewIt_Main AS ViewIt_Main_4
GROUP BY
pend,'Black/African/Caribbean/Black British' AS Ethnicity,SUM(Eth_Black_NewTx) AS NewTx,SUM(Eth_Black_AllInTx) AS AllInTx
FROM
dbo.ViewIt_Main AS ViewIt_Main_3
GROUP BY
pend,'Other ethnic group' AS Ethnicity,SUM(Eth_Other_NewTx) AS NewTx,SUM(Eth_Other_AllInTx) AS AllInTx
FROM
dbo.ViewIt_Main AS ViewIt_Main_2
GROUP BY
pend,age_group
)
AS p
)
AS f
我需要分母是 SubsCategoryId、Area、gender 和 age_group 的给定暂挂中所有种族的总和。
像当前输出一样,我需要创建两列,一列用于 AllInTx 的比例,另一列用于 NewTx。
解决方法
我相当肯定,您可以通过使用 cross apply values
对数据进行逆透视,然后通过窗口函数计算比例值来解决您的问题,从而得到更简单的查询语句:
SELECT
pend,ReportingPeriod,Area,SubsCategoryId,gender,age_group,Ethnicity,NewTx,AllInTx,-- ISNULL(NULLIF( combo catches divide by 0 errors
ISNULL(CAST(NewTx AS DECIMAL(19,4)) / NULLIF(SUM(NewTx) OVER (PARTITION BY pend,age_group),0),0) as NewTxProportion,ISNULL(CAST(AllInTx AS DECIMAL(19,4)) / NULLIF(SUM(AllInTx) OVER (PARTITION BY pend,0) as AllInTxProportion,FROM
(
SELECT
m.pend,CONVERT(char(4),DATEPART(yy,m.pend) - 1) + '/' + RIGHT(CONVERT(char(4),m.pend)),2) AS ReportingPeriod,m.Area,m.SubsCategoryId,m.gender,m.age_group,e.Ethnicity,SUM(e.NewTx) AS NewTx,SUM(e.AllInTx) AS AllInTx
FROM dbo.ViewIt_Main as m
CROSS APPLY (VALUES('White',m.Eth_White_NewTx,m.Eth_White_AllInTx),('Mixed/Multiple ethnic group',m.Eth_Mixed_NewTx,m.Eth_Mixed_AllInTx),('Asian/Asian British',m.Eth_Asian_NewTx,m.Eth_Asian_AllInTx),('Black/African/Caribbean/Black British',m.Eth_Black_NewTx,m.Eth_Black_AllInTx),('Other ethnic group',m.Eth_Other_NewTx,m.Eth_Other_AllInTx)
) as e(Ethnicity,AllInTx
)
GROUP BY
m.pend,e.Ethnicity
) as d;