这是我需要重写以在SQL Server 2008上工作的代码。下面的代码在SQL Server 2012及以上工作,因为它使用了LAG
窗口窗口函数。
有人可以帮助我吗?
LAG(AccountKey) OVER(ORDER BY AccountKey) AS PREC
我想我需要添加一些详细信息
单击此行以查看表格的屏幕截图,其中包含我发送的代码求解的数据。但是我需要重写滞后功能以与SQL 2008
一起使用SELECT AccountKey,
LineName,
AccountName,
GroupKey,
AccountNumber,
ParentAccountKey
INTO tempAccount
FROM
(
SELECT AccountKey,
LineName,
AccountName,
GroupKey,
AccountNumber,
AccountKey AS ParentAccountKey,
LAG(AccountKey) OVER(ORDER BY AccountKey) AS PREC
FROM tempTable2
WHERE GroupKey IS NULL
UNION ALL
SELECT A.AccountKey,
A.LineName,
A.AccountName,
A.GroupKey,
A.AccountNumber,
B.AccountKey AS ParentAccountKey,
B.PREC
FROM tempTable2 A
INNER JOIN
(
SELECT AccountKey,
LineName,
AccountName,
GroupKey,
AccountNumber,
AccountKey AS ParentAccountKey,
LAG(AccountKey) OVER(ORDER BY AccountKey) AS PREC
FROM tempTable2
WHERE GroupKey IS NULL
) B ON A.AccountKey < B.AccountKey
AND (B.PREC IS NULL
OR B.PREC < A.AccountKey)
WHERE A.GroupKey IS NOT NULL
AND B.GroupKey IS NULL
) X
ORDER BY AccountKey;
我们在这里没有完整的图片,因为我们只有一列上的详细信息,但是,这应该可以带您到达需要的地方。
WITH CTE AS (
SELECT YourColumns,
ROW_NUMBER() OVER (ORDER BY AccountKey) AS RN
FROM YoutTable)
SELECT YourColumns
C2.AccountKey
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RN = C2.RN + 1;