根据sql中重复的列ID为重复的行值创建新列

时间:2019-09-18 20:20:15

标签: mysql sql database sorting mysql-5.7

我有一个包含2列的表,第一列称为ID,第二列称为TRACKINGID列中有重复项,我想将所有重复项合并为一行,将重复行中TRACKING中的每个值放入同一行中的新列中,不再重复。

我尝试了一些建议的方法,其中将所有值都连接到一个列中,但是我希望将这些TRACKING的这些ID值放在单独的列中。下面的代码没有达到我的预期。

SELECT ID, TRACKING = 
    STUFF((SELECT DISTINCT ', ' + TRACKING
       FROM #t b 
       WHERE b.ID = a.ID 
      FOR XML PATH('')), 1, 2, '')
FROM #t a
GROUP BY ID

我想要这个:

| ID | TRACKING |
-----------------
| 5  | 13t3in3i |
| 5  | g13g13gg |
| 3  | egqegqgq |
| 2  | 14y2y24y |
| 2  | 42yy44yy |
| 5  | 8i535i35 |

将其变成这样:

| ID |  TRACKING  | TRACKING1 | TRACKING2 |
-----------------
| 5  |  13t3in3i  | g13g13gg  | 8i535i35  |
| 3  |  egqegqgq  |           |           |
| 2  |  14y2y24y  | 42yy44yy  |           |

2 个答案:

答案 0 :(得分:0)

在MySQL中(相对)痛苦的方式是使用相关子查询:

select i.id,
       (select t.tracking
        from t
        where t.id = i.id
        order by t.tracking
        limit 1, 0
       ) as tracking_1,
       (select t.tracking
        from t
        where t.id = i.id
        order by t.tracking
        limit 1, 1
       ) as tracking_2,
       (select t.tracking
        from t
        where t.id = i.id
        order by t.tracking
        limit 1, 2
       ) as tracking_3
from (select distinct id from t
     ) i;

看起来很糟糕,索引为(id, tracking)时,它可能会具有令人惊讶的出色表现。

顺便说一句,使用stuff()的原始代码会将所有内容都放在一栏中:

select id, group_concat(tracking)
from t
group by id;

答案 1 :(得分:-1)

with test_tbl as
(
    select 5 id, 'goog' tracking,'goog' tracking1
    union all
    select 5 id, 'goog1','goo'
    union all
    select 2 , 'yahoo','yah'
    union all
    select 2, 'yahoo1','ya'
    union all
    select 3,'azure','azu'
), modified_tbl as
(
    select id,array_agg(concat(tracking)) Tracking,array_agg(concat(tracking1)) Tracking1 from test_tbl group by 1
)

select id, tracking[safe_offset(0)]  Tracking_1,tracking1[safe_offset(0)]  Tracking_2, tracking[safe_offset(1)] Tracking_3,tracking1[safe_offset(1)] Tracking_4 from modified_tbl where array_length(Tracking) > 1