I have 3 columns/fields as part of a generic list: strID, seq, unit
there are a bunch of strID
s that belong to the same unit and they each have a different seq
. I'm interested in the row that has the minimum seq
per unit
(the leader of the group). How would I accomplish this with a LINQ query (a tsql query would also be fine)?
Following is example data:
strID, seq, unit
aaa, 3, 1
bbb, 2, 1
ccc, 4, 1
ddd, 8, 2
eee, 15,2
fff, 7, 2
My query would get me the following:
leaderID, unit
bbb, 1
fff, 2
source
.GroupBy(row => row.unit)
.Select(g => g.OrderBy(row => row.seq).First());
In T-SQL, you would use
SELECT leaderID, unit
FROM (
SELECT strID, unit, row_number() over(partition by unit order by seq asc) as ranking_within_unit
FROM t
)
WHERE ranking_within_unit = 1
The window functions (OVER()
) are made for this purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With