TSQL结合了多个记录

时间:2014-02-26 20:46:55

标签: tsql

我有一张包含以下内容的表:

Code     ID1        ID2 
Blue     1           2 
Blue                 3 
Blue                 4 
Green    1           5 
Green                10 
Green                12 

我需要结果集:

Code      ID1       ID2 
Blue      1         2
Blue      1         3
Blue      1         4 
Blue      1         5 
Green     1         5
Green     1         10 
Green     1         12 

ID1中的数字并不总是以1开头。

任何想法?我很难过!

1 个答案:

答案 0 :(得分:0)

Drop Table T1
Create table T1( Code varchar(10), Id1 int, Id2 int )
Insert T1 Values
('Blue',   11,  2),
('Blue',   12,  3), 
('Blue', NULL,  4),
('Blue',   15,  5),
('Blue', NULL,  6),
('Green',  23, 21),
('Green',  24, 24),
('Green',NULL, 25),
('Green',NULL, 28),
('Green',  27, 29),
('Red',    35, 33),
('Red',  NULL, 36),
('Red',  NULL, 38)

SELECT 
    A.Code, ISNULL(A. Id1,B.LastId) Id1 , A.Id2 
FROM T1 A
CROSS APPLY( 
            Select Top 1 Id1 as LastId  
            From T1 
            where A.Code = T1.Code and Id2 <= A.Id2
            order by id1 desc   
            ) B