当表中需要相同的字段但具有不同的条件时,是否可以执行此类操作。
我试图像这样做,但有一些东西缺失,这就是为什么它不能正常工作。
;WITH ProductsCTE (PSC_Score_0_11, PSC_Score_12_18, PSC_Score_19_23,
PSC_Score_24_34, PSC_Score_35_50, PSC_Score_51_100,
Total AS
(
SELECT
SUM(CONVERT(int, PSC_Score_0_11)) AS PSC_Score_0_11,
SUM(CONVERT(int, PSC_Score_12_18)) AS PSC_Score_12_18,
SUM(CONVERT(int, PSC_Score_19_23)) AS PSC_Score_19_23,
SUM(CONVERT(int, PSC_Score_24_34)) AS PSC_Score_24_34,
SUM(CONVERT(int, PSC_Score_35_50)) AS PSC_Score_35_50,
SUM(CONVERT(int, PSC_Score_51_100)) AS PSC_Score_51_100,
(SUM(CONVERT(int, PSC_Score_0_11)) + SUM(CONVERT(int, PSC_Score_12_18)) +
SUM(CONVERT(int, PSC_Score_19_23)) + SUM(CONVERT(int, PSC_Score_24_34)) +
SUM(CONVERT(int, PSC_Score_35_50)) + SUM(CONVERT(int, PSC_Score_51_100))) AS Total
FROM
VillageLevelPscData
)
SELECT *
FROM ProductsCTE
WHERE [DISTRICT_NAME] = 'ABC'
UNION ALL
SELECT *
FROM ProductsCTE
WHERE [DISTRICT_NAME] = 'DEF'
我希望将结果作为“PSC_Score_0_11”的总和以及其他地区='ABC'和地区='DEF'的结果,并将它们合并为一个表。
我收到此查询的错误:
关键字“AS”附近的语法不正确。
我想为每个区域得到这样的结果。
答案 0 :(得分:2)
我猜你想要:
select district_name,
sum(CONVERT(int,PSC_Score_0_11 )) as PSC_Score_0_11,
sum(CONVERT(int,PSC_Score_12_18 )) as PSC_Score_12_18,
sum(CONVERT(int,PSC_Score_19_23 )) as PSC_Score_19_23,
sum(CONVERT(int,PSC_Score_24_34 )) as PSC_Score_24_34,
sum(CONVERT(int,PSC_Score_35_50 )) as PSC_Score_35_50,
sum(CONVERT(int,PSC_Score_51_100 )) as PSC_Score_51_100,
(SUM(CONVERT(int,PSC_Score_0_11 )) + SUM(CONVERT(int,PSC_Score_12_18 )) +
SUM(CONVERT(int,PSC_Score_19_23 )) + SUM(CONVERT(int,PSC_Score_24_34 ))
+ SUM(CONVERT(int,PSC_Score_35_50 ))+ SUM(CONVERT(int,PSC_Score_51_100 ))
) as Total
from VillageLevelPscData
group by district_name;
CTE似乎并不特别有用。