Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server select first row from a group

Tags:

sql-server

I have table like this:

a          b 1          23 1          2 1          7 2          9 2          11 

I want to select the first row(order does not matter) from a "GROUP BY a" query , the result should be

a          b 1          23 2          9 

I am using SQL SERVER 2008 how to write the query for this?

like image 785
Rn2dy Avatar asked Sep 08 '11 07:09

Rn2dy


People also ask

Can we use top with GROUP BY clause?

Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.

How do you select only the first rows for each unique value of a column in SQL?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on.

Can we use select * with GROUP BY?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.

How do I select one row in SQL Server?

While the table name is selected type CTRL + 3 and you will notice that the query will run and will return a single row as a resultset. Now developer just has to select the table name and click on CTRL + 3 or your preferred shortcut key and you will be able to see a single row from your table.


2 Answers

select a,b from ( select a,b,row_number() over(partition by a order by b desc) as roworder from myTable ) temp where roworder = 1 

see http://msdn.microsoft.com/en-us/library/ms186734.aspx

like image 130
remi bourgarel Avatar answered Sep 20 '22 00:09

remi bourgarel


If as you indicated, order doesn't matter, any aggregate function on b would be sufficient.

Example Using MIN

SELECT a, b = MIN(b) FROM   YourTable GROUP BY        a 
like image 42
Lieven Keersmaekers Avatar answered Sep 24 '22 00:09

Lieven Keersmaekers