gpt4 book ai didi

SQL 请求 : Count with group by and total to make a percentage on the same line

转载 作者:行者123 更新时间:2023-11-29 12:02:51 24 4
gpt4 key购买 nike

我目前因一个简单的请求而被阻止...:

我有这个数据库:

order | couple | first | second
-------------------------------
1 | A-B | A | B
2 | A-D | A | D
3 | A-C | A | C
4 | A-B | A | B
5 | Y-Z | Y | Z

我想在一行中获得:

order | count | total | percentage
-------------------------------
A-B | 2 | 4 | 50%
A-D | 1 | 4 | 25%
A-C | 1 | 4 | 25%
Y-Z | 1 | 1 | 100%

我可以找到第一部分:订单 | count...但是不可能将它与总数和百分比结合起来(而不是使用子查询...):我在尝试进行结合时遇到了很多不同的错误。

我对第一部分的要求:

SELECT couple,count(couple) 
FROM DATA d1
WHERE exists (
SELECT *
FROM DATA d2
WHERE d1.first = d2.first)
GROUP BY d1.couple;

我对第二部分的要求:

SELECT first, count(first) 
FROM DATA
GROUP BY first;

有人知道提示吗?

最佳答案

我想你想要:

select couple, count(*),
count(*) over (partition by first) as total,
(count(*) * 1.0 / sum(count(*)) over (partition by first) ) as ratio
from t
group by couple, first;

关于SQL 请求 : Count with group by and total to make a percentage on the same line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com