
將行資料轉為欄位:顯示使用者最新信箱
問題:
您的表格中每個使用者有多個郵箱地址,您希望將其展平為列,以便基於建立日期顯示每個使用者的最新三個郵箱地址。
預期輸出:
| 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中文網其他相關文章!