Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

MS SQL Server select rows with max values

Good day

I have Table1:

COLUMN1    COLUMN2   Column3  
----------------------------
Eva           Apple       1
Eva           Apple       2
Eva           Apple       3
Eva           Apple       4
Eva           Apple       5
Eva           Apple       6
Bob           Apple       1
Bob           Samsung     1
Bob           Samsung     2
...           ...        ...

I need

COLUMN1    COLUMN2   Column3
----------------------------
Eva           Apple       6
Bob           Samsung     2
Bob           Apple       1
...           ...        ...

How i can setup string for select only rows with MAX values in Column3 ?

My version of string is :

SELECT MAX(Column3) , [column2], [Column2] 
FROM Table1
WHERE Column3 =  MAX ;

Thanks for Opinions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use row_number

Select top (1) with ties *
   from table1 
   order by row_number() over (partition by Column1, Column2 order by Column3 desc)

Other way is to use outer query:

Select * from (
   Select *, RowN = row_number() over (partition by Column1, Column2 order by Column3 desc) from table1 ) a
   Where a.RowN = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...