我正在尝试运行以下查询:
Select T, COUNT(T) as CountOf, (COUNT(T)*100)/(SUM(COUNT(T))) AS percen FROM
(
select prod as T, x,y,z from table1
UNION ALL select prod as T, x,y,z from table2
UNION ALL select prod as T, x,y,z from table3
)
AS m
GROUP BY T ORDER BY COUNT(T) DESC;
上述查询给出了错误。我能够在没有第3个参数的情况下成功运行查询,即(COUNT(T)*100)/(SUM(COUNT(T))) AS percent
(计算第2个参数的百分比分布,即CountOf
)
但是当我包含百分比参数时,它会给出错误。任何有关这方面的帮助将不胜感激。
答案 0 :(得分:1)
您需要将SUM
更改为SUM OVER
,但MySQL不支持此功能:
SELECT T, COUNT(T) AS CountOf,
(COUNT(T)*100)/(SUM(COUNT(T)) OVER ()) AS percen
FROM
(
SELECT prod AS T, x,y,z FROM table1
UNION ALL
SELECT prod AS T, x,y,z FROM table2
UNION ALL
SELECT prod AS T, x,y,z FROM table3
) AS m
GROUP BY T
ORDER BY COUNT(T) DESC;
答案 1 :(得分:0)
我不喜欢使用distinct,但如果您使用的是sql server,可以试试
Select DISTINCT T, COUNT(*) OVER (PARTITION BY T) as CountOf, ((COUNT(*) OVER (PARTITION BY T) * 100) / COUNT(*) OVER ()) AS percen FROM
(
select prod as T, x,y,z from table1
UNION ALL select prod as T, x,y,z from table2
UNION ALL select prod as T, x,y,z from table3
)
AS m
CTE选项
WITH cteUnion AS (
SELECT prod AS T, x,y,z FROM table1
UNION ALL
SELECT prod AS T, x,y,z FROM table2
UNION ALL
SELECT prod AS T, x,y,z FROM table3
),
cteUnionWithTotalCount AS (
SELECT *, COUNT(*) OVER () AS TotalCount FROM cteUnion
)
SELECT T, COUNT(*) AS CountOf, ((COUNT(*) * 100)/ TotalCount) AS percen
FROM cteUnionWithTotalCount
GROUP BY T, TotalCount
ORDER BY COUNT(*)