我想创建一个查询来计算数据库中整体策略的销售百分比。 这些政策分为两个单独的标题
我想要的代码应该显示
我已尝试编写此代码的脚本(请参阅下文),但无法让它们正确运行。
语法1:
SELECT b.PRODUCT_NAME, b.POLICIES_SOLD, 100.00*(b.POLICIES_SOLD/SUM(b.POLICIES_SOLD)) AS'PERC_SALES'
FROM
(
SELECT a.PRODUCT_NAME, COUNT(a.PRODUCT_NAME) AS
'POLICIES_SOLD'
FROM
(SELECT PRODUCT_NAME FROM [ATLANTIS\jjudge].
[ALL_POLICIES_201706_NL]
UNION ALL
SELECT PRODUCT_NAME FROM [ATLANTIS\jjudge].
[ALL_POLICIES_201706_UL])a GROUP BY PRODUCT_NAME)b ;
语法2:
SELECT a.PRODUCT_NAME, a.[POLICIES SOLD], 100.00*(a.[POLICIES SOLD]/SUM(a.[POLICIES SOLD]))
FROM
(SELECT PRODUCT_NAME, COUNT(*) AS 'POLICIES SOLD'FROM
[ATLANTIS\jjudge].[ALL_POLICIES_201706_NL] GROUP BY PRODUCT_NAME
UNION ALL
SELECT PRODUCT_NAME, COUNT(*) AS 'POLICIES SOLD' FROM
[ATLANTIS\jjudge].[ALL_POLICIES_201706_UL] GROUP BY
PRODUCT_NAME)a ;
语法3:
SELECT b.PRODUCT_NAME, COUNT(b.PRODUCT_NAME) AS
'POLICIES_SOLD', 100.00*
(COUNT(b.PRODUCT_NAME)/SUM(SELECT(PRODUCT_NAME))
FROM
(SELECT COUNT(*) AS 'POLICY_COUNT' FROM [ATLANTIS\jjudge].[ALL_POLICIES_201706_NL]
UNION ALL
SELECT COUNT(*) AS 'POLICY_COUNT' FROM [ATLANTIS\jjudge].[ALL_POLICIES_201706_UL])a)) AS 'PERC_SALES'
FROM
(SELECT PRODUCT_NAME FROM [ATLANTIS\jjudge].
[ALL_POLICIES_201706_NL]
UNION ALL
SELECT PRODUCT_NAME FROM [ATLANTIS\jjudge].
[ALL_POLICIES_201706_UL])b GROUP BY PRODUCT_NAME;
答案 0 :(得分:0)
我想你想要一个Window功能。将语法1的第一行修改为:
SELECT
b.PRODUCT_NAME,
b.POLICIES_SOLD,
100.00*b.POLICIES_SOLD/SUM(b.POLICIES_SOLD) OVER () AS 'PERC_SALES'
答案 1 :(得分:0)
您可以使用带窗口函数的单个聚合查询来执行此操作:
SELECT p.PRODUCT_NAME, COUNT(*) AS POLICIES_SOLD,
COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () as PERC_SALES
FROM ((SELECT PRODUCT_NAME
FROM [ATLANTIS\jjudge].[ALL_POLICIES_201706_NL]
) UNION ALL
(SELECT PRODUCT_NAME
FROM [ATLANTIS\jjudge].[ALL_POLICIES_201706_UL]
)
) p
GROUP BY PRODUCT_NAME;