列的唯一值

时间:2013-04-10 05:53:33

标签: sql-server sql-server-2008

我的表格如下所示,我需要获得colA和colb的唯一值以及colC的第一个值

ID    ColA   ColB   ColC
1      A1     B1    c1
2      A1     B1    c2
3      A2     B2    c3
4      A2     B2    c4

预期结果

A1  B1   C1
A2  B2   c3

对此有任何帮助

1 个答案:

答案 0 :(得分:5)

只需使用MIN()这是一个聚合函数,并按ColA and ColB

对记录进行分组
SELECT  ColA, ColB, MIN(ColC) ColC
FROM    TableName
GROUP   BY ColA, ColB

更新1

WITH records
AS
(
    SELECT  ID, ColA, ColB, ColC,
            ROW_NUMBER() OVER (PARTITION BY ColA, ColB ORDER BY ID) rn
    FROM    TableName
)
SELECT  ColA, ColB, ColC
FROM    records
WHERE   rn = 1