所有按日期分组的concat列

5t7ly7z5  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我有下表

| date | name   | val | country | sex |
|------|--------|-----|---------|-----|    
| 2013 | Mark   | 01  | USA     | M   |
| 2013 | John   | 02  | Germany | M   |
| 2013 | Carla  | 84  | Croatia | F   |
| 2013 | Carlos | 49  | France  | M   |
| 2013 | Doe    | 47  | India   | M   |
| 2014 | Mark   | 27  | Spain   | M   |
| 2014 | John   | 59  | Germany | M   |
| 2014 | Carla  | 26  | Croatia | F   |
| 2014 | Carlos | 30  | France  | M   |
| 2014 | Doe    | 49  | India   | M   |
| 2015 | Mark   | 55  | USA     | M   |
| 2015 | John   | 95  | Germany | M   |
| 2015 | Carla  | 85  | Croatia | F   |
| 2015 | Carlos | 75  | France  | M   |
| 2015 | Doe    | 65  | India   | M   |
| 2016 | Mark   | 16  | USA     | M   |
| 2016 | John   | 20  | Germany | M   |
| 2016 | Carla  | 18  | Croatia | F   |
| 2016 | Carlos | 29  | France  | M   |
| 2016 | Doe    | 35  | India   | M   |
| 2017 | Mark   | 39  | Rusia   | M   |
| 2017 | John   | 32  | Germany | M   |
| 2017 | Carla  | 21  | Croatia | F   |
| 2017 | Carlos | 29  | France  | M   |
| 2017 | Doe    | 44  | India   | M   |

我需要在查询中得到以下结果

|      | Mark       | John         | Carla        | Carlos      | Doe        |
|------|------------|--------------|--------------|-------------|------------|
| 2013 | 01/USA/M   | 02/Germany/M | 84/Croatia/M | 49/France/M | 47/India/M |
| 2014 | 27/Spain/M | 20/Germany/M | 26/Croatia/M | 30/France/M | 49/India/M |
| 2015 | 55/USA/M   | 95/Germany/M | 85/Croatia/M | 75/France/M | 65/India/M |
| 2016 | 16/USA/M   | 20/Germany/M | 18/Croatia/M | 16/France/M | 16/India/M |
| 2017 | 39/Rusia/M | 32/Germany/M | 21/Croatia/M | 16/France/M | 16/India/M |

别介意数据只是随机的。
基本上,最主要的一组是按日期。
致以最诚挚的问候。

avkwfej4

avkwfej41#

您可以使用条件聚合来实现这一点—如果您知道结果集中需要的所有名称:

select date,
       max(case when name = 'Mark' then concat_ws('/', val, country, sex) end) as Mark,
       max(case when name = 'John' then concat_ws('/', val, country, sex) end) as John,
       max(case when name = 'Carla' then concat_ws('/', val, country, sex) end) as Carla,
       . . .
from t
group by date;

如果您事先不知道所有的名称,那么您就有一个动态透视问题,需要使用动态sql( prepare / exec ).

相关问题