第一个和最后一个row_number

时间:2014-10-01 02:10:12

标签: sql sql-server-2008 tsql

我有一张包含许多不同公司的表格,每张公司的订单数量从1只到可能的n

我用过

ROW_NUMBER() OVER (PARTITION BY CompanyName ORDER BY OrderDate) AS Orders

这给了我一个如下的样本

Comp1   1
Comp2   1
Comp3   1
Comp3   2
Comp3   3
Comp3   4
Comp4   1
Comp4   2
Comp4   3

如何查看表格并选择每家公司的第一张和最后一张记录?最终得到:

Comp1   1
Comp2   1
Comp3   1
Comp3   4
Comp4   1
Comp4   3

2 个答案:

答案 0 :(得分:3)

您可以使用row_number()两次或count()

select c.*
from (select c.*,
             row_number() over (partition by CompanyName order by OrderDate) as seqnum,
             count(*) over (partition by CompanyName) as cnt
      from companies c
     ) c
where seqnum = 1 or seqnum = cnt;

答案 1 :(得分:0)

select * from Orders
where (CompanyName , OrderDate) in (
    select CompanyName , min(OrderDate) from Orders group by CompanyName 
    union all
    select CompanyName , max(OrderDate) from Orders group by CompanyName 
)