如何在 SQL 服务器中编写循环加入?

How to write Joins in loop in SQL server?

我的 table 中有以下类型的数据,我需要获得以下类型的输出。

U.Id  Current_Id  Previous_Id Date reason
01        aa          null     21   xyz
01        bb           aa      24   yxz
01        cc           bb      24   out
01        dd           cc      25   tot
01        aaa         null     11   yyz
01        bbb         aaa      12   zyy

前四条为一组,后两条为一组。我们可以通过 current_id 和 Previous_ID 列来识别这一点。我需要以下类型的输出。

输出:

O1 - aa - 21 - 25 - tot
01 - aaa - 11 - 12 -zyy

对于每组,我需要第一个和最后一个记录日期。我怎样才能在 ms sql 中实现这一点?

您可以使用递归通用Table表达式(rCTE)递归遍历数据,然后得到各自的MINMAX:

WITH YourTable AS(
    SELECT *
    FROM (VALUES('01','aa',NULL,21),
                ('01','bb','aa',24),
                ('01','cc','bb',24),
                ('01','dd','cc',25),
                ('01','aaa',NULL,11),
                ('01','bbb','aaa',12))V([U.Id],Current_Id,Previous_Id,[Date])), --A column with a . in the name is a bad idea.
                                                                               --Date is an odd name for something that is clearly an int
--Solution
rCTe AS(
    SELECT YT.[U.Id],
           YT.Current_Id,
           YT.Previous_Id,
           YT.[Date],
           YT.Current_Id AS Start_Id
    FROM YourTable YT
    WHERE Previous_ID IS NULL
    UNION ALL
    SELECT YT.[U.Id],
           YT.Current_Id,
           YT.Previous_Id,
           YT.[Date],
           r.Start_Id
    FROM YourTable YT
         JOIN rCTE r ON YT.Previous_Id = r.Current_Id)
SELECT r.[U.Id],
       r.Start_Id AS Current_Id,
       MIN(r.[Date]) AS StartDate,
       MAX(r.[Date]) AS EndDate
FROM rCTE r
GROUP BY r.[U.Id],
         r.Start_Id;