我有一个2列表:
Category | Count
Total 100
Red 30
Blue 40
Yellow 30
您如何编写查询以生成以下输出? 我只能提出一步:
1)获取百分比列 - 回合(红色计数/总计数)* 100)
希望得到你的帮助以获得下面的输出。谢谢!
Category | Count | Percent
Total 100 100
Red 30 30
Blue 40 40
Yellow 30 30
答案 0 :(得分:2)
另一种选择是
#standardSQL
SELECT t.*, ROUND(t.Count * 100.0 / total.Count) Percent
FROM t, (SELECT Count FROM t WHERE category = 'Total') total
您可以使用问题中的虚拟数据进行测试/播放
#standardSQL
WITH t AS (
SELECT 'Total' Category, 100 Count UNION ALL
SELECT 'Red', 30 UNION ALL
SELECT 'Blue', 40 UNION ALL
SELECT 'Yellow', 30
)
SELECT t.*, ROUND(t.Count * 100.0 / total.Count) Percent
FROM t, (SELECT Count FROM t WHERE category = 'Total') total
答案 1 :(得分:0)
您可以使用窗口功能:
select t.*,
count * 100.0 / max(case when category = 'Total' then count end) over () as percent
from t