有几行信息到一行

时间:2016-02-29 16:14:16

标签: sql teradata

您好我需要将2个表与客户信息合并。表2告诉我们是否有关于电子邮件,地址和电话号码的客户信息,但数据的结构使每个客户有3行。有没有办法合并这两个表,以便我每个客户只获得一行,但有所有的联系信息?

表1:

id  customerID  ... ...

1   11 

2   99

和表2:

id  customerID  Channel Y_N

1   11          Email    Y

2   11          Address  Y

3   11          Phone    N

4   99          Email    N

5   99          Address  Y

6   99          Phone    N

我的代码就是这个

TABLE 1
left join(
    select customerID, 
    case when Y_N='Y' and Channel='Email' then 1 else 0 end as Email
    FROM table2 
    where Channel='Email')a
    on table1.customerID=a.customerID
Left join(
    select customerID, 
    case when Y_N='Y' and Channel='Address' then 1 else 0 end as Address
    FROM table2
    where Channel='Address') b
    on table1.customerID=b.customerID
Left join(
    select customerID, 
    case when Y_N='Y' and Channel='Phone' then 1 else 0 end as Phone
    FROM table2
    where Channel='SMS') c
    on  table1.customerID=c.customerID

实际上可以完成这项工作,但如果我将来再做一次,那么还有更聪明的方法吗?

谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用单个usong条件聚合(= pivot)替换这三个联接:

TABLE1
left join(
    select customerID, 
       max(case when Y_N='Y' and Channel='Email' then 1 else 0 end) as Email
       max(case when Y_N='Y' and Channel='Address' then 1 else 0 end) as Address
       max(case when Y_N='Y' and Channel='Phone' then 1 else 0 end) as Phone
    FROM table2 
    GROUP BY 1) a
    on table1.customerID=a.customerID

这可能更有效,请查看说明......

答案 1 :(得分:0)

那么,如果它有效,为什么要改变呢?但是,如果你必须,可能是这样的:

SELECT
    c.*,
    IF(e.Y_N='Y',1,0) AS Email,
    IF(a.Y_N='Y',1,0) AS Address,
    IF(p.Y_N='Y',1,0) AS Phone
FROM table1 AS c
   LEFT JOIN table2 AS e ON(c.customerID=e.customerID AND Channel='Email')
   LEFT JOIN table2 AS a ON(c.customerID=a.customerID AND Channel='Address')
   LEFT JOIN table2 AS p ON(c.customerID=p.customerID AND Channel='Phone')

另外,我真的没有理由在table2中为每个客户提供三行。如果可能的话,最好将其改为

customerID|Email|Address|Phone
    11    |  1  |   1   |  0
    99    |  0  |   1   |  0

这样你就可以做到

SELECT * FROM table1 AS a LEFT JOIN table2 AS b ON a.customerID=b.customerID

答案 2 :(得分:0)

如果您希望将来有新的频道,可以使用它来动态地将频道添加为列:

DECLARE @SearchList     varchar(MAX)
DECLARE @sql            varchar(MAX)

select @SearchList = COALESCE(@SearchList, '') + ', [' + cast(Channel as VARCHAR(100)) + ']' 
from (select distinct channel from #table2) a

set @sql = 'select CustomerID, ' + RIGHT(@SearchList, LEN(@SearchList)-1) +'
from
(select CustomerID, Channel, Y_N
    from #table2) as t
pivot
(
    max(Y_N)
    for Channel in (' + RIGHT(@SearchList, LEN(@SearchList)-1) + ')
) as pvt'

exec(@sql)