2013-05-30 71 views
2

在SQL Server 2008 R2:使用該表在一列中選擇行與重複值

CREATE TABLE mytest(
    id [bigint] IDENTITY(1,1) NOT NULL, 
    code [bigint] NULL, 
    sequence_number [int] NULL 
); 

這個查詢:

SELECT id, code, sequence_number 
    FROM mytable 

返回此數據:

id  code sequence_number 
    1  381  0 
    2  381  1 
    3  382  0 
    4  382  1 
    5  383  0 
    6  383  1 
    7  383  1 
    8  384  0 
    9  384  1 
    10  385  0 
    11  385  1 
    12  385  2 
    13  386  0 
    14  386  1 
    15  386  1 
    16  386  2 
    17  387  0 
    18  387  1 
    19  387  1 
    20  387  2 
    21  387  3 
    22  387  3 
    23  388  0 
    24  388  1 
    25  388  1 
    26  388  2 
    27  388  2 
    28  389  0 
    29  389  1 

怎麼辦我SELECT只是這些行:

7 383 1 
15 386 1 
19 387 1 
22 387 3 
25 388 1 
27 388 2 

這些是MAX(id)行,其中有多個記錄具有相同的sequence_number。我希望代碼和sequence_number的每個唯一組合的所有最高ID。

所以,實際上我只想選擇「重複的」sequence_number記錄。

我該怎麼做?

+0

你試過我答? – vikas

回答

1

使用本

SELECT 
    MAX(t1.Id) as ID, 
    t1.code, 
    t1.sequence_number 
FROM mytest t1 
INNER JOIN mytest t2 
ON t1.id <> t2.id 
AND t1.code = t2.code 
AND t1.sequence_number = t2.sequence_number 
GROUP BY t1.code, 
    t1.sequence_number 
    ORDER BY ID 
1

select code,MAX(sequence_number) from mytest group by code

2

試試這個: -

Select ID,code,sequence_number from 
(
    Select ID, 
     code, 
     [rn] = row_number() over (partition by code,sequence_number order by id), 
     sequence_number 
    from yourTable 
)s 
where rn > 1 

演示在SQL FIDDLE