繁体   English   中英

Sql - 将重复行值拆分为新列

[英]Sql - split recurrring row values into new columns

我有一个查询列出了在不同州出现的同名城市

+----------+-------+
| city     | state |
+----------+-------+
| x        | melb  | 
| x        | syd   | 
| y        | bris  | 
| y        | ACT   | 
+----------+-------+

我想要这样的格式

+----------+-------+--------+--------+
| city1    | state1|city2   |state2  |
+----------+-------+--------+--------+
| x        | melb  | x      | syd    |
| y        | bris  | y      | ACT    |
+----------+-------+--------+--------+

如果您想要对,请使用自联接:

select c1.city, c1.state, c2.state
from cities c1 join
     cities c2
     on c1.city = c2.city and c1.state < c2.state;

但这并不令人满意。 我宁愿在一行中查看给定城市的所有州。 为此,可以使用字符串聚合——具体功能因数据库而异。 但是 SQL 标准指定listagg()

select city, listagg(state, ', ') within group (order by state)
from cities
group by city;

在不了解您的 dbms 的情况下,很难提出更好的解决方案。 如果一个城市只有两个州,请查看:

模式和插入语句:

 create table mytable (city     varchar(10), state varchar(50));
 insert into mytable values ('x','melb');
 insert into mytable values ('x','syd');
 insert into mytable values ('y','bris');
 insert into mytable values ('y','ACT');  

询问:

 select city city1,max(state) State1,city city2,min(state)state2 from mytable
 group by city

Output:

城市1 状态1 城市2 状态2
X syd X 梅尔布
是的 布里斯 是的 行为

db<> 在这里摆弄

I think we could user inner query to separate the original table into 2 tables: (city1, state 1) and (city2, state 2), with condition as city 1 = city 2, state 1 <> state 2. And then join them一起

暂无
暂无

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

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