Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only first row from a specific Column with same value

I have a complicated SQL Query that returns about 10 000 rows. In my query i have a OrderNr and a lot of rows contains the same OrderNr. Now i want to grab only the first 1 of the rows with the same OrderNr. This is only for the OrderNr column and not for any other column. I mean i have same values in some other columns also but there i want all the rows.

Here i made some easy example for you

Fiddle Example

Goal is too get the output

1,Bruno,Dan
2,Johnson,Lars
4,Jordan, Derreck
5,Johnson,Peter

Here is Firstname the same as my OrderNr

How do i do this?

like image 456
user2210516 Avatar asked Sep 05 '26 15:09

user2210516


1 Answers

You can partition by orderNumbers and rank the orders by ids. When selecting only rows with rownumber 1, you get the expected result.

;WITH orders AS (
     SELECT *, 
        Row_Number() over (PARTITION BY OrderNr ORDER BY <ID>) rn       
    FROM T  
)
SELECT * FROM orders WHERE rn=1

With your fiddle: http://sqlfiddle.com/#!6/07780/11

like image 199
flo Avatar answered Sep 08 '26 09:09

flo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!