[[ОТВЕТ ОБНОВЛЕНО - Для учета ОП исправлены исходные данные]]
@ В PreQL упоминается обработка данных как иерархии.
Я объявил здесь пару переменных таблицы дляпростой вырезать / вставить / проверить запрос ...
declare @customers TABLE (CustomerCode int, CurrenctCustomerCode int)
insert into @customers values (123456, null)
insert into @customers values (123455, null)
insert into @customers values (123454, null)
insert into @customers values (123453, null)
declare @history TABLE (CustomerCodeX int, CustomerCodeY int)
insert into @history values (123456, 123455)
insert into @history values (123455, 123454)
insert into @history values (123454, 123453)
insert into @history values (123453, 123452)
insert into @history values (123452, null)
Нам нужно найти точку привязки для иерархии - и мы можем сделать это с помощью подзапроса, который находит торговые идентификаторы, которые не являются«предыдущие» идентификаторы для последующих торговых идентификаторов.
select c.*
from @customers c
left join @history h
on c.CustomerCode = h.CustomerCodeY
where h.CustomerCodeX is null
Помещение подзапроса с помощью в мой оригинальный CTE выглядит примерно так:
; with cte (CCX, CCY, CCC)
as
(
select h1.CustomerCodeX, h1.CustomerCodeY, x.CustomerCode
from @history h1
join (select c.* from @customers c left join @history h on c.CustomerCode = h.CustomerCodeY where h.CustomerCodeX is null) x
on h1.CustomerCodeX = x.CustomerCode
union all
select
h.CustomerCodeX,
h.CustomerCodeY,
cte.CCC
from @history h
join cte on h.CustomerCodeX = cte.CCY
)
select CCX as CustomerCode, CCC as CurrentCustomerCode from cte
Вывод:
CustomerCode CurrentCustomerCode
------------ -------------------
123456 123456
123455 123456
123454 123456
123453 123456
123452 123456
Надеюсь, это полезно.