且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server选择不同

更新时间:2023-01-20 22:18:31

这听起来像你想'最大每组'。



一种方法是使用窗口函数 ROW_NUMBER 对每个组中的行进行编号,然后选择行号为1的那些行:

  SELECT ColA,ColB,ColC,ColD 
FROM

SELECT
ColA,ColB, ColC,Co lD,
ROW_NUMBER(由ColB分区,ColC按ORD排序)从
FROM table1
)T1
WHERE rn = 1


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 combination 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