我在 PostgreSQL 中有一个表,如下所示:
--------------------------------------------------------------
Item1 | Item2 | Item3 | Item4 |Value1| Value2| Value3| Value4|
--------------------------------------------------------------
我想要一个查询,该查询将显示如下表:
ItemHead| ValueHead
---------------
Item1 | Value1|
---------------
Item2 | Value2|
----------------
Item3 | Value3|
----------------
Item4 | Value4|
---------------
Use a single SELECT
with a LATERAL
加入到一个VALUES
表达。这比多个更短、更快SELECT
声明:
SELECT v.*
FROM tbl, LATERAL (
VALUES
(item1, value1)
, (item2, value2) -- data types must be compatible
, (item3, value3)
, (item4, value4)
) v ("ItemHead", "ValueHead"); -- your desired column names
Related:
- 将一行转换为列数较少的多行 https://stackoverflow.com/questions/45201170/convert-one-row-into-multiple-rows-with-fewer-columns/45204205#45204205
- 在多列上选择 DISTINCT https://dba.stackexchange.com/a/102702/3684
- Postgres:将单行转换为多行(unpivot) https://stackoverflow.com/questions/47077068/postgres-convert-single-row-to-multiple-rows/47077708#47077708
注意:您添加了标签crosstab /questions/tagged/crosstab。但是Postgres函数crosstab()
从额外的tablefunc module https://www.postgresql.org/docs/current/tablefunc.html是用来pivoting,而此任务则相反,有时称为不旋转。有关的:
- PostgreSQL 交叉表查询 https://stackoverflow.com/questions/3002499/postgresql-crosstab-query/11751905#11751905
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)