【问题标题】:How to write Joins in loop in SQL server? [closed]如何在 SQL Server 中编写循环连接? [关闭]
【发布时间】:2020-11-21 05:52:52
【问题描述】:

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

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 中实现这一点?

【问题讨论】:

  • 您很可能需要将 Top 和 Min 函数与 group by 结合起来。不过你的问题不是很清楚。

标签: tsql sql-server-2012 sql-server-2016


【解决方案1】:

您可以使用递归公用表表达式 (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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2013-12-21
    • 2019-08-29
    • 2016-06-06
    相关资源
    最近更新 更多