第二栏的MINIMUM,第一和第三

时间:2015-02-27 08:07:51

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

DECLARE @Foo TABLE (Id INT, PozId INT, Val INT)
        INSERT @Foo (Id, PozId, Val)
        VALUES
        (1, 1, 34),
        (1, 2, 976),
        (2, 1, 235),
        (2, 2, 792),
        (3, 2, 456),
        (3, 3, 123)

如何从上面的查询中获得这样的结果?

(1, 1, 34)
(2, 1, 235)
(3, 2, 456)

提前谢谢

1 个答案:

答案 0 :(得分:2)

这会带来你想要的结果。查询分区您的ID并选择最低的PozitionId。

DECLARE @Foo TABLE
(
    Id INT, PozId INT, Val INT
);

INSERT @Foo
    (Id, PozId, Val)
VALUES
    (1, 1, 34)
    , (1, 2, 976)
    , (2, 1, 235)
    , (2, 2, 792)
    , (3, 2, 456)
    , (3, 3, 123);

SELECT Id, PozId, Val
FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY Id ORDER BY PozId) AS RowNo, *
    FROM @Foo
    ) AS T
WHERE RowNo = 1;