如何将数据从一列分为两列

时间:2020-02-03 15:32:04

标签: sql pivot

我在SQL中查询了这些结果,并尝试将它们分别分为两列:

ID          Lat/Long     Geocoding

 1           Lat          27.4996954
 2           Lat          39.4236405
 3           Lat          40.4483913
 4           Long         -76.9341023
 5           Long         -81.0817888
 6           Long         -95.5968665
 .           .            .
 .           .            .
350          Lat          33.9760517

我想要的结果:

  ID         Lat          Long

   1       40.4483913     -97.303731
   .          .             .
   .          .             .
   .          .             .
 350       33.9760517      -81.0817888 

1 个答案:

答案 0 :(得分:0)

查询

我不得不假设您将使用ID列将长和纬配对。

带有where条件的简单连接可以解决此问题。

SELECT dlat.id, dlat.geocoding AS lat,
       dlong.geocoding AS lon
FROM geodata dlat inner join geodata dlong
ON  dlat.id = dlong.id     
WHERE
  dlat.latlong='lat'
  AND dlong.latlong='long';    

提琴:https://www.db-fiddle.com/f/vSzZ4YPJC3NTewoE4k7t8z/1

DDL

create table geodata(
id integer,
latlong varchar(5),
geocoding float);

insert into geodata values( 1   ,   'Lat',  27.4996954  );
insert into geodata values( 2   ,   'Lat',  39.4236405  );
insert into geodata values( 3   ,   'Lat',  40.4483913  );
insert into geodata values( 4   ,   'Lat',  -76.9341023 );
insert into geodata values( 5   ,   'Lat',  -81.0817888 );
insert into geodata values( 6   ,   'Lat',  -95.5968665 );

insert into geodata values( 1   ,   'Long', 47.4996954  );
insert into geodata values( 2   ,   'Long', 59.4236405  );
insert into geodata values( 3   ,   'Long', 60.4483913  );
insert into geodata values( 4   ,   'Long', -56.9341023 );
insert into geodata values( 5   ,   'Long', -61.0817888 );
insert into geodata values( 6   ,   'Long', -75.5968665 );