2014-10-01 167 views
0

我有很多不同的公司的表格,每一批訂單,從只有1到可能的n第一個和最後ROW_NUMBER

我用

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 

回答

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; 
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 
) 
相關問題