gpt4 book ai didi

用于查找唯一列和连接两列结果的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 12:52:22 26 4
gpt4 key购买 nike

我有一个包含以下信息的表A

+----+-------+-------+-----+--------+-----------+
| ID | jobID | user | ip | time | userAgent |
+----+-------+-------+-----+--------+-----------+
| 1 | uuid1 | user1 | IP1 | Epoch1 | JSONB1 |
| 2 | uuid1 | user1 | IP2 | Epoch2 | JSONB2 |
| 3 | uuid2 | user3 | IP3 | Epoch3 | JSONB3 |
| 4 | uuid1 | user2 | IP4 | Epoch2 | JSONB2 |
| 5 | uuid1 | user4 | IP5 | Epoch4 | JSONB4 |
| 6 | uuid1 | user1 | IP2 | Epoch2 | JSONB2 |
+----+-------+-------+-----+--------+-----------+

我只想要唯一出现的 (jobID & user) 并按以下方式连接用户的结果。

+-------+-------------------+-------------+
| jobID | user | count(user) |
+-------+-------------------+-------------+
| uuid1 | user1,user2,user4 | 3 |
| uuid2 | user3 | 1 |
+-------+-------------------+-------------+

现在我写了一个类似

的查询
SELECT
DISTINCT
"jobID",
"user"
FROM
"A"
ORDER BY
"jobID",
"user";

它给了我

+-------+-------+
| jobID | user |
+-------+-------+
| uuid1 | user1 |
| uuid1 | user1 |
| uuid2 | user3 |
| uuid1 | user2 |
| uuid1 | user4 |
+-------+-------+

最佳答案

您应该按 "jobID" 对数据进行分组,并使用 distinct 的聚合函数:

select 
"jobID",
string_agg(distinct "user", ',') as users,
count(distinct "user")
from "A"
group by "jobID"
order by "jobID";

关于用于查找唯一列和连接两列结果的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50855871/

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