在SQL中多次遍历记录

问题描述 投票:0回答:2

我正在编写一个场景,我想在表中遍历同一客户端的记录。

我的表结构是:

enter image description here

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

enter image description here

create table #temp1(cid int,cvid int, date1 date, clone int)
insert into #temp1
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)

create table #person(cid int)
insert into #person values(43),(44),(45)


select top 1 with ties
    t.cid
    ,t.cvid
    ,clone = (select max(t2.cvid) from #temp1 t2 )
    ,t.date1
from #temp1 t
order by row_number() over (partition by cid order by date1)


drop table #temp1,#person

Rextester链接:https://rextester.com/NQNB22767

有什么帮助?!

sql sql-server
2个回答
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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.