Mine SQL Query返回几列但只返回一行。我需要将这一行和列的名称转换为两列 - 首先是列的名称,第二列是行值。由于某些原因,我不能使用交叉表。
我想要执行的操作如下所示。 之前:
Column1 | Column2 | Column3 | Column4
---------+---------+---------+--------
Value1 | Value2 | Value3 | Value4
我希望得到这个:
Cols | Vals
--------+---------
Column1 | Value1
Column2 | Value2
Column3 | Value3
Column4 | Value4
答案 0 :(得分:2)
这样做你想要的吗?
SELECT
'Column1' AS Cols
, Column1 AS Vals
FROM Table
UNION ALL
SELECT
'Column2' AS Cols
, Column2 AS Vals
FROM Table
UNION ALL
SELECT
'Column3' AS Cols
, Column3 AS Vals
FROM Table
UNION ALL
SELECT
'Column4' AS Cols
, Column4 AS Vals
FROM Table
答案 1 :(得分:0)
select 'Column1' as Cols, Column1 as Vals from YourTable
union all
select 'Column2', Column2 from YourTable
union all
select 'Column3', Column3 from YourTable
union all
select 'Column4', Column4 from YourTable
答案 2 :(得分:0)
尝试使用tablefunc扩展名中的交叉表。 http://www.postgresql.org/docs/9.0/static/tablefunc.html
它应该完全符合您的要求。
您可以像这样安装扩展程序:
CREATE EXTENSION tablefunc;