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

时间:2018-06-14 10:57:23

标签: sql postgresql

我有表格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 |
+-------+-------+

3 个答案:

答案 0 :(得分:1)

使用string_agg()

SELECT jobid, string_agg(user, ','), count(*) as num_users
FROM A
GROUP BY jobid;

如果您不想要重复,可以添加distinct

SELECT jobid, string_agg(distinct user, ','), count(distinct user) as num_users
FROM A
GROUP BY jobid;

答案 1 :(得分:1)

您应该按"jobID"对数据进行分组,并将汇总函数与distinct一起使用:

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

答案 2 :(得分:0)

这肯定会给你想要的输出。

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