SQL中的记录遍历

时间:2018-11-07 19:23:22

标签: sql sql-server

我正在研究一种方案,该方案要遍历表中同一Client的记录。

我的表结构是:

enter image description here

我当前的查询正在生成最后一个服务ID和第一个服务ID。但是,我希望结果如下:

enter image description here

future.get(120, TimeUnit.SECONDS);

上个月的链接:https://rextester.com/NQNB22767

有帮助吗?!

2 个答案:

答案 0 :(得分:2)

这看起来正在产生预期的结果...

    CREATE TABLE #temp1 (
        cid INT,
        cvid INT,
        date1 DATE,
        clone INT
    );
    INSERT INTO #temp1(cid, cvid, date1, clone) VALUES
        ('43', '1001', '1/1/2015', NULL),
        ('43', '1002', '2/1/2015', 1001),
        ('43', '1003', '3/1/2015', NULL),
        ('43', '1004', '4/1/2015', 1003),
        ('43', '1005', '4/2/2015', 1004),
        ('43', '1006', '4/3/2015', 1005),
        ('43', '1007', '4/5/2015', NULL),
        ('43', '1008', '4/6/2015', 1007);

CREATE UNIQUE NONCLUSTERED INDEX ixf_temp_notclone
    ON #temp1 (clone, cvid)
    INCLUDE (cid, date1)
    WHERE clone IS NULL;

CREATE UNIQUE NONCLUSTERED INDEX ixf_temp_clone 
    ON #temp1 (clone)
    INCLUDE (cvid)
    WHERE clone IS NOT NULL;


    WITH    
        cte_recursion AS (
            SELECT 
                t.cid,
                t.cvid,
                pid = cvid,
                t.date1,
                t.clone
            FROM
                #temp1 t
            WHERE 
                t.clone IS NULL
            UNION ALL
            SELECT 
                r.cid,
                r.cvid,
                pid = t.cvid,
                r.date1,
                t.cvid
            FROM
                cte_recursion r
                JOIN #temp1 t
                    ON r.pid = t.clone
            )

    SELECT 
        r.cid,
        r.cvid,
        clone = MAX(r.clone),
        r.date1
    FROM
        cte_recursion r
    GROUP BY 
        r.cid,
        r.cvid,
        r.date1;

结果:

cid         cvid        clone       date1
----------- ----------- ----------- ----------
43          1001        1002        2015-01-01
43          1003        1006        2015-03-01
43          1007        1008        2015-04-05

答案 1 :(得分:0)

SQL Server具有标准的olap函数FIRST_VALUE()和LAST_VALUE(),我认为这比ROW_NUMBER()更好。