Query for crosstab view

放肆的年华 提交于 2019-12-11 15:03:51

问题


I have a table in PostgreSQL like below:

--------------------------------------------------------------
Item1 | Item2 | Item3 | Item4 |Value1| Value2| Value3| Value4|
--------------------------------------------------------------

I want a query which will show this table like below:

ItemHead| ValueHead
---------------
Item1 | Value1|
---------------
Item2 | Value2| 
----------------
Item3 | Value3| 
----------------
Item4 | Value4|
---------------

回答1:


Use a single SELECT with a LATERAL join to a VALUES expression. That's shorter and faster than multiple SELECT statements:

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:

  • Convert one row into multiple rows with fewer columns
  • SELECT DISTINCT on multiple columns
  • Postgres: convert single row to multiple rows

Note: You added the tag crosstab. But the Postgres function crosstab() from the additional tablefunc module is used for pivoting, while this task is the opposite, sometimes referred to as unpivoting. Related:

  • PostgreSQL Crosstab Query



回答2:


Simply use UNION ALL

SELECT item1, value1 FROM your_tab
UNION ALL
SELECT item2, value2 FROM your_tab
UNION ALL
SELECT item3, value3 FROM your_tab
UNION ALL
SELECT item4, value4 FROM your_tab


来源:https://stackoverflow.com/questions/47133450/query-for-crosstab-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!