根据Teradata中的某些条件将多个行连接为一列

时间:2020-07-16 00:09:32

标签: teradata

我有一张桌子,如下表

id   color   date 

1    red     01/01
1    red     01/02
1    yellow  01/03
1    red     02/01
2    red     01/01
2    blue    01/02
2    blue    02/02
3    red     01/01
4    red     02/01

理想的输出应该是:

id    pattern 
1     (red, yellow) to (red)
2     (red, blue) to (blue)
3     (red)
4     (red)

结果显示两件事:

  1. 一个月内的独特模式
  2. 在时间范围内将唯一模式汇总在一起

例如,我们可以看到id_1的模式从1月(红色,黄色)开始发生变化,但是2月只有一种模式(红色)发生变化。因此最终输出应为(红色,黄色)至(红色)

我现在的查询是

select drv.id, extract(month from date) as month,
trim(trailing',' from (XMLAGG(TRIM(color)',' order by date)(varchar(10000)))) as pattern from
(select id, color,
lag(color)over(partition by id, extract(month from date) order by date) as prev_color
from table
qualify prev_color <> color
) as drv
group by id, extract(month from date)

查询不完整,因为它没有捕获每个月的移动,但是我们有可能按月返回吗?

有什么方法可以混合使用XMLAGG和进行分区?还是有人可以提出任何想法?

通过评论中提到的F​​red的方法1,可以通过以下查询获得答案:

select drv1.id, 
trim(trailing',' from (XMLAGG(TRIM(color)'-' order by date)(varchar(10000)))) as pattern_mthly from

(
select drv.id, extract(month from date) as month,
trim(trailing',' from (XMLAGG(TRIM(color)',' order by date)(varchar(10000)))) as pattern from
(select id, color,
lag(color)over(partition by id, extract(month from date) order by date) as prev_color
from table
qualify prev_color <> color
) as drv
group by id, extract(month from date)
) as drv1
group by id

谢谢

0 个答案:

没有答案