简体   繁体   中英

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?

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

;WITH CTE as
(
  SELECT PersonID, LastName, FirstName,
  row_number() over (partition by Firstname order by PersonID) rn
  FROM Persons
)
SELECT PersonID, LastName, FirstName
FROM CTE
WHERE rn = 1

Try something like this:

SELECT * FROM Persons p1
where p1.PersonID = (select min(PersonID) from persons p2 where p2.firstname=p1.firstname)

You could achieve the expected result using two steps, without CTEs and WINDOW FUNCTIONs .

First step: GROUP your rows by FirstName and choose a minimum PersonID for each of them

Second step: Use a self-join to get LastName value for that minimum PersonId we obtained in step first.

SELECT foo.PersonID, b.LastName, foo.FirstName
FROM(
  SELECT 
    MIN(PersonID) AS PersonID,
    FirstName 
  FROM Persons 
  GROUP BY FirstName
  ) foo
  INNER JOIN Persons b ON foo.PersonID = b.PersonID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM