SQL 使用重复 ID 的组连接
SQL group concat with duplicate ID's
我正在尝试从 table 组合 week_num,分组 bby Driver_id。但是 group_concat 不会保留重复的 ID,但我的要求是要有它们。
有什么办法可以实现吗?
你可以尝试使用子查询 & self-join
查询 1:
SELECT t2.*,t1.Consolidate_weeks
FROM (
SELECT Driver_id,GROUP_CONCAT(Week_num) Consolidate_weeks
FROM T
GROUP BY Driver_id
) t1 INNER JOIN T t2
ON t1.Driver_id = t2.Driver_id
| Driver_id | Week_num | Consolidate_weeks |
|-----------|----------|-------------------|
| 1 | Week 1 | Week 1,Week 2 |
| 2 | Week 1 | Week 1,Week 2 |
| 3 | Week 1 | Week 1,Week 2 |
| 4 | Week 1 | Week 1,Week 2 |
| 1 | Week 2 | Week 1,Week 2 |
| 2 | Week 2 | Week 1,Week 2 |
| 3 | Week 2 | Week 1,Week 2 |
| 4 | Week 2 | Week 1,Week 2 |
编辑
我看到了你的评论并编辑了问题,如果你正在使用 amazon-redshift 你可以尝试使用 LISTAGG 而不是 GROUP_CONCAT
我正在尝试从 table 组合 week_num,分组 bby Driver_id。但是 group_concat 不会保留重复的 ID,但我的要求是要有它们。 有什么办法可以实现吗?
你可以尝试使用子查询 & self-join
查询 1:
SELECT t2.*,t1.Consolidate_weeks
FROM (
SELECT Driver_id,GROUP_CONCAT(Week_num) Consolidate_weeks
FROM T
GROUP BY Driver_id
) t1 INNER JOIN T t2
ON t1.Driver_id = t2.Driver_id
| Driver_id | Week_num | Consolidate_weeks |
|-----------|----------|-------------------|
| 1 | Week 1 | Week 1,Week 2 |
| 2 | Week 1 | Week 1,Week 2 |
| 3 | Week 1 | Week 1,Week 2 |
| 4 | Week 1 | Week 1,Week 2 |
| 1 | Week 2 | Week 1,Week 2 |
| 2 | Week 2 | Week 1,Week 2 |
| 3 | Week 2 | Week 1,Week 2 |
| 4 | Week 2 | Week 1,Week 2 |
编辑
我看到了你的评论并编辑了问题,如果你正在使用 amazon-redshift 你可以尝试使用 LISTAGG 而不是 GROUP_CONCAT