选择具有非重复指定字段的行(Transact-SQL)

时间:2012-02-04 08:48:33

标签: sql sql-server sql-server-2008 tsql

现在我几乎无法解释我的目的:

我有以下选择

SELECT        id, way_id, node_id, sort
FROM            Relations
WHERE        (way_id = 107187465)

但是行16999和17001在字段 node_id 中具有相似的值。我怎么能除了其中一个呢?

enter image description here

3 个答案:

答案 0 :(得分:3)

以下内容将仅返回ID最高的行。如果有合理的索引(在way_id和id上),这应该表现良好。

SELECT  R.id, R.way_id, R.node_id, R.sort 
FROM    Relations R
WHERE   R.way_id = 107187465
AND     NOT EXISTS (
    SELECT  *
    FROM    Relations R2
    WHERE   R2.way_id = R.way_id
    AND     R2.id > R.id
)

...或者,使用ROW_NUMBER()...

SELECT  R.id, R.way_id, R.node_id, R.sort
FROM    (
    SELECT  *,
            ROW_NUMBER() OVER(PARTITION BY way_id ORDER BY id DESC) AS RN
    FROM Relations
) R
WHERE   R.way_id = 107187465
AND     R.RN = 1

答案 1 :(得分:3)

此未经测试的查询会为您提供ID最高的查询。

SELECT        R1.id, 
              R1.way_id, 
              R1.node_id, 
              R1.sort
FROM          Relations R1
WHERE        R1.way_id = 107187465
AND R1.id = (SELECT MAX(R2.id) FROM Relations R2
             WHERE R1.node_id = R2.node_id)

答案 2 :(得分:1)

试试这个:

SET NOCOUNT ON
DROP TABLE #Relations
CREATE TABLE #Relations(ID int, way_id int, node_id int, sort int)
INSERT INTO  #Relations VALUES (16997, 107187465, 1232361697, 1)
INSERT INTO  #Relations VALUES (16998, 107187465, 1232361496, 2)
INSERT INTO  #Relations VALUES (16999, 107187465, 1232361625, 3)
INSERT INTO  #Relations VALUES (17000, 107187465, 1232361954, 4)
INSERT INTO  #Relations VALUES (17001, 107187465, 1232361625, 5)
INSERT INTO  #Relations VALUES (17002, 107187465, 1232361937, 6)
INSERT INTO  #Relations VALUES (17003, 107187465, 1232361302, 7)
INSERT INTO  #Relations VALUES (17004, 107187465, 1232361878, 8)
INSERT INTO  #Relations VALUES (17005, 107187465, 1232361365, 9)

SET NOCOUNT OFF
SELECT  id, way_id, node_id, sort
FROM    #Relations
WHERE   (way_id = 107187465)

DELETE
FROM    #Relations
FROM    #Relations
JOIN    (
        -- select minimum id: this we'll keep
        SELECT  MIN(#Relations.ID) Id,
                #Relations.way_id,
                #Relations.node_id
        FROM    #Relations
        JOIN    (
                -- get all duplicated rows
                SELECT      way_id, node_id
                FROM        #Relations
                GROUP BY    way_id, node_id
                HAVING      COUNT(*) > 1
                ) duplicates
            ON  #Relations.way_id = duplicates.way_id AND
                #Relations.node_id = duplicates.node_id
        GROUP BY #Relations.way_id, #Relations.node_id
        ) stay
    ON  #Relations.way_id = stay.way_id AND
        #Relations.node_id = stay.node_id AND
        #Relations.id != stay.id
-- comment next line to remove all duplicates
WHERE   (#Relations.way_id = 107187465)

SELECT  id, way_id, node_id, sort
FROM    #Relations
WHERE   (way_id = 107187465)