简体   繁体   English

SQL选择联接表

[英]SQL select joining tables

If I have a table with the following data in MySQL: 如果我在MySQL中有一个包含以下数据的表:

id       Name       Value
1          A          4
1          A          5
1          B          8
2          C          9

how do I get it into the following format? 如何将其转换为以下格式? is that even possible? 那有可能吗?

id         Column   Column   Column    Column   Column    Column
1            A        4         A        5         B        8
2            c        9

You can use conditional aggregation: 您可以使用条件聚合:

select id,
       max(case when seqnum = 1 then name end) as name_1,
       max(case when seqnum = 1 then value end) as value_1,
       max(case when seqnum = 2 then name end) as name_2,
       max(case when seqnum = 2 then value end) as value_2,
       max(case when seqnum = 3 then name end) as name_3,
       max(case when seqnum = 3 then value end) as value_3
from (select t.*,
             row_number() over (partition by id order by value) as seqnum
      from t
     ) t
group by id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM