在分组依据之前将行值存储为新列

时间:2018-07-25 14:08:47

标签: sql sql-server

任何人都知道如何分组,但要保留一个独立的列?我把UNPIVOT弄乱了,但是找不到很好的解释来帮助我编写代码。有人有解决方案吗?

我有如下数据:

acct contact email phone
1     44      abc  NULL
1     33      NULL 123
2     2       xxx  NULL
2     22      NULL 456

我使用

select acct,max(email) as email, max(phone) as phone from my_table 
group by acct

结束:

acct email phone
1    abc 123
2    xxx  456

但我的最终目标是按照以下方式分组并为电话和电子邮件创建一个单独的联系人列:

acct contact_email email phone contact_phone
1     44           abc  123    33
2     2            xxx  456    22

2 个答案:

答案 0 :(得分:2)

您似乎想要简单的聚合:

select acct, 
       max(case when phone is null then contact end) as contact_email,
       max(email) as email, max(phone) as phone, 
       max(case when email is null then contact end) as contact_phone
from table t
group by acct;

答案 1 :(得分:0)

尝试以下方法,可能会有所帮助,没有子查询,也没有组

SELECT t1.acct,t1.contact contact_email,t1.email,  t2.phone,t2.contact contact_phone  FROM my_table t1 inner join my_table t2 on t1.acct=t2.acct
 where t1.email is not null and t2.phone is not null