tsql - 在一行中返回重复的行ID

时间:2014-02-05 15:03:36

标签: sql sql-server

我在表格中找到了“重复记录”。虽然,我声称它们是重复的,但它们只是PK是一个标识列 - 所以它们不是真正的重复(但基于其他列 - 它们是)。

我目前将这些数据放在一个表格中,格式如下:

ID -> identity column 
Row -> indicates the sequential row number 
RowNumber -> indicates that two of the rows are identical 

例如:

ID    Row      RowNumber
500    1        1000 
501    2        1000 
305    1        1050 
306    2        1050

我想为每个行号

返回一行中的ID

例如,上述结果集将为:

500  501
305  306 

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

单向,将ROW_NUMBEROVER-clause

一起使用
WITH CTE AS
(
    SELECT ID,Row,RowNumber, 
       RN = ROW_NUMBER()OVER (PARTITION BY RowNumber
                              ORDER BY Row)
    FROM CTE
)
SELECT ID,Row,RowNumber FROM CTE WHERE RN = 1

如果要删除重复项,请将SELECT替换为

DELETE FROM CTE WHERE RN > 1 

答案 1 :(得分:0)

CREATE TABLE #Table 
(
ID         INT,
"Row"      INT,
RowNumber  INT
)

INSERT INTO #Table 
VALUES
  (500,1,1000),
  (501,2,1000),
  (305,1,1050),
  (306,2,1050)

CASE语句有效:

SELECT 
    RowNumber,
    MAX(CASE WHEN "Row" = 1 THEN ID ELSE NULL END) AS "1", 
    MAX(CASE WHEN "Row" = 2 THEN ID ELSE NULL END) AS "2"
FROM #Table
GROUP BY RowNumber

PIVOT is an alternative

SELECT
    RowNumber,
    "1",
    "2"
FROM
    (SELECT "Row",ID, RowNumber FROM #Table) AS SourceTable
    PIVOT
    (
    MAX(ID) 
    FOR "Row" IN ("1","2")
    ) AS PivotTable