我在 Postgres 10.4 中有下表。
Name Email EmailType
--------------------------------------
John [email protected] Primary Email
John [email protected] Secondary Email
John [email protected] Work Email
Jack [email protected] Primary Email
Jack [email protected] Secondary Email
Jim [email protected] Primary Email
如何根据名称(假设该名称在此表中是唯一的)和电子邮件类型列中的值在 col4 中分配值。对于每个人(
Name
列),我想检查他们有多少电子邮件类型(EmailType
列),然后将人名和电子邮件类型连接到一个新列中。
像下面这样。
Name Email EmailType Col4
-----------------------------------------------------------------------------------------
John [email protected] Primary Email John: Primary Email, Secondary Email, Work Email
John [email protected] Secondary Email
John [email protected] Work Email
Jack [email protected] Primary Email Jack: Primary Email, Secondary Email
Jack [email protected] Secondary Email
Jim [email protected] Primary Email Jim: Primary Email
我想过使用
CASE
语句,但无法让它发挥作用。对此的任何帮助将不胜感激。
您可以使用窗口函数和字符串聚合来做到这一点。
select name, email, emailtype,
case when rn = 1 then string_agg(emailtype, ', ') over (partition by name) end col4
from
(
select *, row_number() over (partition by name order by emailtype) rn from the_table
) t;
正如@jarlh 评论的那样,使用视图。