简体   繁体   English

将表(列)值转换为独立的行

[英]Convert table (column) values into independent rows

I have a table with primary key as (state+city) and other columns (product1, product2, product3, product4) . 我有一个主键为(state+city)和其他columns (product1, product2, product3, product4) I am trying to create a new table where each row will correspond to (state+city) & (one of) products + some static_value columns. 我正在尝试创建一个新表,其中每一行将对应于(state+city)和(其中一个)产品+一些static_value列。 How do I do it in a PostgreSQL query? 我如何在PostgreSQL查询中执行此操作?

It's probably better to see examples of input and output data that I am looking at. 最好看一下我正在研究的输入和输出数据的例子。 I checked various examples of converting rows to columns in MySQL or SQL Server on this forum but they don't seem to help me. 我在这个论坛上检查了在MySQL或SQL Server中将行转换为列的各种示例,但它们似乎对我没有帮助。

Example data sheet ('Input Table' and 'Desired Output' tabs) 示例数据表('输入表'和'所需输出'选项卡)

https://docs.google.com/spreadsheets/d/1qQZhWXB_h80HfaDi6VOqeOs7CVNyW9gwtEd-GRqLHKc/edit#gid=1581374593 https://docs.google.com/spreadsheets/d/1qQZhWXB_h80HfaDi6VOqeOs7CVNyW9gwtEd-GRqLHKc/edit#gid=1581374593

You can use union all selecting one column at a time as below. 您可以使用union all一次选择一列,如下所示。 You can add other column (TextA, TextB, Date...) to each SELECT query as per requirement. 您可以根据需要为每个SELECT查询添加其他列(TextA,TextB,Date ...)。

SELECT State,City,'Product1' Product, Product1 Value FROM your_table
UNION ALL
SELECT State,City,'Product2' Product, Product2 Value FROM your_table
UNION ALL
SELECT State,City,'Product3' Product, Product3 Value FROM your_table
UNION ALL
SELECT State,City,'Product4' Product, Product4 Value FROM your_table

You can cross join with the individual columns turned to rows: 您可以将各个列交叉连接到行:

select t.state, t.city, x.product
form the_table t
  cross join lateral ( 
     values (t.product1), (t.product2), (t.product3)
  ) as x(product)

Or bit more compact: 或者更紧凑:

select t.state, t.city, x.product
form the_table t
  cross join unnest(array[t.product1, t.product2, t.product3]) as x(product)

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

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