如何在订购后从每个组中选择前1名

时间:2010-07-30 17:32:38

标签: .net linq tsql

我有3列/字段作为通用列表的一部分:strID, seq, unit
有一堆strID属于同一个单位,每个seq都有不同的seq。我对每个unit(组的领导者)最小 strID, seq, unit aaa, 3, 1 bbb, 2, 1 ccc, 4, 1 ddd, 8, 2 eee, 15,2 fff, 7, 2 的行感兴趣。如何使用LINQ查询完成此操作(tsql查询也可以)?

以下是示例数据:

leaderID, unit
bbb, 1
fff, 2

我的查询会给我以下内容:

{{1}}

4 个答案:

答案 0 :(得分:5)

source
  .GroupBy(row => row.unit)
  .Select(g => g.OrderBy(row => row.seq).First());

答案 1 :(得分:4)

在T-SQL中,您将使用

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

窗口函数(OVER())就是为此目的而创建的。

答案 2 :(得分:0)

尝试使用此尺寸:

select x.strID, a.unit
  from (select unit, MIN(seq) as seq from myTable group by unit) a
  join myTable x 
    on a.unit = x.unit and a.seq = x.seq

答案 3 :(得分:0)

试试这个..

set nocount on
go
WITH MyTable AS
(  
SELECT 'aaa' [strID], 3 seq, 1 unit
UNION SELECT 'bbb', 2, 1
UNION SELECT 'ccc', 4, 1
UNION SELECT 'ddd', 8, 2
UNION SELECT 'eee', 15,2
UNION SELECT 'fff', 7, 2
)
,
MinSequence AS
(
    SELECT Unit, Min (Seq) MinSequence
    FROM MyTable
    Group BY Unit
)
SELECT MT.*
FROM MyTable MT
    JOIN MinSequence MS
        ON MT.Unit = MS.Unit
        AND MT.Seq = MS.MinSequence

结果

strID seq         unit
----- ----------- -----------
bbb   2           1
fff   7           2