【问题标题】:Convert rows to column in PostgreSQL在 PostgreSQL 中将行转换为列
【发布时间】:2019-10-03 04:00:42
【问题描述】:

我想在 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);

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

【问题讨论】:

  • 预期结果是什么?
  • 我有编辑问题。
  • 请输入此图表。请勿粘贴图片。只需输入TABLE test; 并将输出放在这里。更好的是,如果您真的关心并想要投票……粘贴 DDL。 CREATE TABLE AS SELECT,你会得到快乐。

标签: postgresql crosstab


【解决方案1】:

也许这会有所帮助。

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

【讨论】:

  • @EvanCarroll 写一个答案,我对交叉表的了解有限。
  • 我的也是。我总能得到我想要的,但这不是我的强项。通过输入任何这张图片,你超越了我愿意做的事情。我对此有0-tolerance。我在用文本制作 DDL 时划清界限。不管怎样,继续挖人。这就是我们如何让自己变得更好。它很可能与 ORDER BY 1,2 有关。文档提到它。我学到了一些东西。我只是无法用你的 Rexster 观察它。
  • Crosstab 绝对是 PostgreSQL 的一个薄弱环节。
  • 如果事实上,按 id 排序,给出了正确的 row_order,但不是名称值。
  • 如果交叉表的工作方式与 mssql PIVOT 相同,则无法获得观察到的结果。
猜你喜欢
  • 2015-09-11
  • 2012-12-14
  • 2019-10-15
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2022-07-07
相关资源
最近更新 更多