【问题标题】:teradata concatenating rows based on a columnteradata 基于列连接行
【发布时间】:2015-12-30 04:20:24
【问题描述】:

我有一张像下面这样的表格

Cstmr_ID | PPM | prepaid |home_phone|srvc_num
1        |Y    |N        |N         |0422222222
1        |Y    |N        |N         |0433333333
1        |N    |N        |Y         |0333333333 
2        |y    |N        |N         |0455555555
2        |N    |N        |Y         |0355555555

现在我想要一张这样的桌子。

Cstmr_id  | PPM_srvc_num         |prepaid_srvc_num|home_phone_srvc_num
1         |0422222222,0433333333 |                |0333333333
2         |0455555555            |                |0355555555

【问题讨论】:

  • 什么版本的 Teradata?你自己尝试过什么吗?

标签: sql teradata


【解决方案1】:

您要做的是转置您的表,然后对连接的记录进行分组。自 Teradata 14.10 以来,有 TD_UNPIVOT 函数可以转置,但我还没有使用它。

如果您可以在结果中的一个 Cstmr_id 的同一列中使用固定的数字上限 (N),您可以使用 case 语句和 row_number() 来模拟转置和组连接。

select Cstmr_id
, max(case when PPM='Y' and rn=1 then srvc_num else null end) 
||  coalesce(max(case when PPM='Y' and rn=2 then ','||srvc_num else null end),'')
...
||  coalesce(max(case when PPM='Y' and rn=N then ','||srvc_num else null end),'')
as PPM_srvc_num
-- add the further lines for prepaid ='Y' and home_phone='Y'
from (
  select *
  , row_number() over (partition by Cstmr_ID, PPM, prepaid, home_phone) as rn 
  from your_table 
) dt
group by 1

我还没有测试过上面的代码,但我实际上已经为自己做过这种类型的转换,所以在为你的实际表完全写出来之后它应该可以工作

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 2019-02-04
    • 2018-01-21
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2011-10-05
    • 2020-11-03
    相关资源
    最近更新 更多