
将行数据转为列:显示用户最新邮箱
问题:
您的表格中每个用户有多个邮箱地址,您希望将其展平为列,以便基于创建日期显示每个用户的最新三个邮箱地址。
预期输出:
| user_name | user_id | email1 | email2 | email3 |
|---|---|---|---|---|
| Mary | 123 | [email protected] | [email protected] | [email protected] |
| Joe | 345 | [email protected] | NULL | NULL |
解决方案:
为此,您可以利用 PostgreSQL 中 tablefunc 模块的 crosstab() 函数:
<code class="language-sql">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 <= 3
ORDER BY user_id, rn
$$,
'VALUES (1),(2),(3)'
) AS ct (user_id integer, user_name text, email1 text, email2 text, email3 text);</code>解释:
注意:
以上是如何将用户电子邮件的行数据转置为 PostgreSQL 中的列?的详细内容。更多信息请关注PHP中文网其他相关文章!