大家好,我有以下CTE ...我想要做的是拥有一个Id,然后是状态的连接列表
所以例如...如果我有
1, 1234, Hot
2, 1234, Cold
3, 1234, Warm
我想以
结束1234,'Hot,Cold,Warm'
我的CTE
with recursive temp_table(RowNumber, Id, Status) as (
select
row_number() over (order by OBJECT_STATUS ) as RowNumber
,OBJECT_ID
,cast(OBJECT_STATUS as varchar(100)) as Status
from
CORE_ORDER_STATUS
where
OBJECT_ID = 'OR000008387722'
union all
select
a.RowNumber + 1 as NextOne
,b.OBJECT_ID
,a.Status || ',' || cast(b.OBJECT_STATUS as varchar(5)) as Status
from
CORE_ORDER_STATUS b
inner join
temp_table a
on
a.Id = b.OBJECT_ID
where
a.RowNumber = b.NextOne
)
select * from temp_table;
答案 0 :(得分:1)
您从CTE的SELECT返回每一行。您想要具有最高RowNumber
的记录,我认为该记录需要包含HAVING RowNumber=MAX(RowNumber)
以及要返回的列的GROUP BY
子句。
答案 1 :(得分:1)
假设Rob Paller对你的问题的解释是正确的(我认为是这样的),这就是我如何处理这个问题,以及一些针对源数据的kludgy volatile临时表:
create volatile table vt_test as (
select
'1234' as object_id,
cast ('Hot' as varchar(1000)) as object_status
) with data
primary index (object_id)
on commit preserve rows;
insert into vt_test values ('1234','Cold');
insert into vt_test values ( '1234','Warm');
insert into vt_test values ( '5678','Red');
insert into vt_test values ( '5678','Blue');
insert into vt_test values ( '5678','Green');
create volatile table vt_two as(
select
row_number() over (partition by object_id order by object_status ) as RN,
object_id,
object_status
from
vt_test) with data
primary index (object_id)
on commit preserve rows;
with RECURSIVE CTE (RN,Object_id,Object_Status,counter) as (
SELECT
RN,
object_id,
Object_Status,
cast(1 as integer)
from
vt_two
where RN = 1
UNION ALL
select
b.rn,
b.object_id,
a.object_status || ',' || b.object_status as Object_Status,
counter + 1
from
vt_two a
inner join cte b
on a.object_id = b.object_id
and a.rn = b.counter + 1
)
select
*
from
CTE
qualify rank() over (partition by object_id order by counter desc) = 1;
哪个会给你:
1 1234 Warm,Hot,Cold 3
1 5678 Red,Green,Blue 3
最后的qualify
子句是关键。评论它,它的作用非常清楚。
你必须非常小心递归CTE,至少在Teradata中。编写一个基本上永远不会结束的查询非常容易。