在 PostgreSQL 中将行转换为列

nag*_*agi 6 postgresql crosstab

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

在此输入图像描述

预期输出:

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);
Run Code Online (Sandbox Code Playgroud)

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

McN*_*ets 8

也许这会有所帮助。

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 |
+----------+-------+--------+--------+--------+
Run Code Online (Sandbox Code Playgroud)

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

在这里检查: http: //rextester.com/MFWAW58518