开发者

SQL Server Select Distinct

开发者 https://www.devze.com 2022-12-30 10:10 出处:网络
I want to write a query like this: For a table that has these columns: ColA ColB ColC, ColD select first(ColA, ColB, ColC, ColD)

I want to write a query like this:

For a table that has these columns: ColA ColB ColC, ColD

select first(ColA, ColB, ColC, ColD) distinct(ColB, ColC) from table order by ColD

The query is supposed to order the table by ColD, then group the results by the co开发者_Python百科mbination of ColB and ColC (they may have different data types) and returns the first rows (with all the columns of the table) in the groups.

How is it possible in MS SQL Server 2005?


It sounds like you want 'max per group'.

One way is to use the windowing function ROW_NUMBER to number the rows in each group, and then select only those rows with row number 1:

SELECT ColA, ColB, ColC, ColD
FROM
(
    SELECT
         ColA, ColB, ColC, ColD,
         ROW_NUMBER(PARTITION BY ColB, ColC ORDER BY ColD) AS rn
    FROM table1
) T1
WHERE rn = 1
0

精彩评论

暂无评论...
验证码 换一张
取 消