SQL如何获得总数的百分比
在SQL中,我只是尝试使用每行百分比的桌子。我到处都是,但不能完全理解。 计数(*)/sum(count(count(*))()
是接近的,但这占所有部分的百分比。
数据:
id = ['a','b',...]
方案= [1,2,3,4]
SQL:
SELECT * FROM(
SELECT
ID,
Scenario,
count(*) as count,
FROM `table`
GROUP BY `ID`,
`Scenario`
)
pivot(
sum(count) as total
for Scenario in (1,2,3,4)
)
当前输出:
ID /方案 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
A | 2 | 4 | 1 | 3 |
B | 2 | 7 | 5 | 6 |
这很好,但是我也想显示每行的%,所以每一行应总计100%。
所需的输出:
ID /方案 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
A | 20% | 40% | 10% | 30% |
B | 10% | 45% | 25% | 30% |
我该怎么做?谢谢。
In SQL I am trying to do a table with percentages for each row only. I've looked everywhere but can't quite get it. count(*)/sum(count(*)) over ()
is close but that does % of everything.
Data:
ID = ['A','B',...]
Scenario = [1,2,3,4]
SQL:
SELECT * FROM(
SELECT
ID,
Scenario,
count(*) as count,
FROM `table`
GROUP BY `ID`,
`Scenario`
)
pivot(
sum(count) as total
for Scenario in (1,2,3,4)
)
Current output:
Id / Scenario | 1 | 2 | 3 | 4 |
---|---|---|---|---|
A | 2 | 4 | 1 | 3 |
B | 2 | 7 | 5 | 6 |
This is good, but I also want to display this as % of each row so each row should add up to 100%.
Desired output:
Id / Scenario | 1 | 2 | 3 | 4 |
---|---|---|---|---|
A | 20% | 40% | 10% | 30% |
B | 10% | 45% | 25% | 30% |
How can I do this? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,基本上,您尝试为A-1做的是A-1/A?方案/总计 * 100会给您正确的价值吗?然后只是concat a%标志
So basically what you would try to do for A-1 is A-1/A? Would Scenario/Total * 100 give you the correct value? then just concat a % sign