在PostgreSQL

时间:2017-01-14 17:13:34

标签: postgresql crosstab

我想在PostgreSQL中将行转换为列。我希望所有变量都针对各自的id.but它不起作用。

enter image description here

预期输出:

myvar   desc    fname   lname        sdate          edate         id     
title1  desc1   cina    jhon    1483920000000   1484524800000     14
title2  desc2   jhon    lname2  1483920000000   1483910000000     16
title3  desc3   diesel  zier    1483920000000   1484524800000     17



 SELECT * FROM crosstab(
 'SELECT  name, value, id FROM test ORDER  BY id') AS (
 "myVar" text, "desc" text, "fname" text, "lname" text,"sdate" text,"edate" text, "value" text ,"containerid" bigint);

错误:     错误:返回类型无效     SQL状态:42601     详细信息:SQL rowid数据类型与返回的rowid数据类型不匹配。

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助。

此处需要

ORDER BY 1,2

select *
    from crosstab (
        'select id, name, value
        from tt1
        order by 1,2')
    AS (row_name int, col1 text, col2 text, col3 text, col4 text);

+----------+-------+--------+--------+--------+
| row_name | col1  |  col2  |  col3  |  col4  |
+----------+-------+--------+--------+--------+
|    14    | desc1 |  chen  |  john  | title1 |
+----------+-------+--------+--------+--------+
|    15    | desc2 | fname2 | lname2 | title2 |
+----------+-------+--------+--------+--------+
|    16    | desc4 | deiser |  ziel  | title3 |
+----------+-------+--------+--------+--------+

实际上,列应命名为:col1,col2,col3,col4,...

在此处查看:http://rextester.com/MFWAW58518