且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Postgres - 将行转置为列

更新时间:2023-11-18 21:17:10

Use crosstab() 来自 tablefunc 模块.

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

我对第一个参数使用了美元引用,没有特殊含义.在查询字符串中转义单引号很方便,这是一个常见的情况:

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient to escape single quotes in the query string, which is a common case:

详细说明和说明:

特别是对于额外的列":

And in particular, for "extra columns":

这里的特殊困难是:

  • The lack of key names.
    --> We substitute with row_number() in a subquery.

不同数量的电子邮件.
-->我们限制为最大值.外部 SELECT
中的三个并使用带有两个参数的 crosstab(),提供可能的键列表.

The varying number of emails.
--> We limit to a max. of three in the outer SELECT
and use crosstab() with two parameters, providing a list of possible keys.

注意ORDER BY中的NULLS LAST.