2014-02-06 52 views
1

我想寫一個查詢,將在一個查詢中產生頂行和底行。我可以找到一個或另一個,但我不能同時排在一起。如何在一個查詢中返回頂部和底部的行?

以下是我有:

SELECT (SELECT top(1) Lastname + ',' + firstname FROM 
CUSTOMERS 
    join orders on customerID = customerID_fk 
    join orderDetails on orderID = orderID_fk 
group by Lastname + ',' + firstname 
order by sum(quantity) desc); 

這裏是一個鏈接:http://sqlfiddle.com/#!6/51ad4/129

什麼是讓我期待的回報最好的做法?

+0

你在尋找最大和最小總和記錄嗎? –

+0

我正在查找訂購最多商品的人員以及訂購人數最少的人員。 – MrWhale

回答

2

這裏使用的窗口函數的方法:

select name 
from (SELECT Lastname + ',' + firstname as name, 
      row_number() over (order by sum(quantity)) as rownum, 
      count(*) over() as cnt 
     FROM CUSTOMERS 
      join orders on customerID = customerID_fk 
      join orderDetails on orderID = orderID_fk 
     group by Lastname + ',' + firstname 
    ) t 
where rownum = 1 or rownum = cnt; 

這裏是另一種方式:

with cte as (
     SELECT Lastname + ',' + firstname as name, sum(quantity) as qty 
     FROM CUSTOMERS 
      join orders on customerID = customerID_fk 
      join orderDetails on orderID = orderID_fk 
     group by Lastname + ',' + firstname 
) 
select top 1 name from cte order by qty union all 
select top 1 name from cte order by qty desc; 
0

我認爲你正在尋找Union

SELECT top(1) Lastname + ',' + firstname FROM 
CUSTOMERS 
    join orders on customerID = customerID_fk 
    join orderDetails on orderID = orderID_fk 
group by Lastname + ',' + firstname 
order by sum(quantity) desc Union 
SELECT top(1) Lastname + ',' + firstname FROM 
CUSTOMERS 
    join orders on customerID = customerID_fk 
    join orderDetails on orderID = orderID_fk 
group by Lastname + ',' + firstname 
order by sum(quantity) asc 
0

也許我們可以爲此使用子查詢。這個想法是找出最大和最小訂購項目。然後我們可以使用現有的查詢並在(Sub Query Here)中寫入類似sum(quantity)的東西。

或者你可以檢查以下工作?

SELECT (SELECT Top(2) Lastname + ',' + firstname FROM 
CUSTOMERS 
    join orders on customerID = customerID_fk 
    join orderDetails on orderID = orderID_fk 
group by Lastname + ',' + firstname 
order by sum(quantity) desc having sum(quantity) = 
Max(Sum(quantity)) or Sum(quantity)=Min(Sum(Quantity)) 
+0

這給了我一個不正確的語法錯誤 – MrWhale

相關問題