2010-03-26 49 views
2

我需要對我做什麼是一種先進的排序。我有這樣的兩個表:複雜的訂單子句?

 
Table: Fruit 

fruitid | received | basketid 
    1  20100310 2 
    2  20091205 3 
    3  20100220 1 
    4  20091129 2 

Table: Basket 
id | name 
1 Big Discounts 
2 Premium Fruit 
3 Standard Produce 

我什至不知道我可以清楚地說出我要如何排序(這也許是我似乎無法編寫代碼來做到這一點的很大一部分原因,大聲笑)。

我做一個連接查詢,需要排序,所以一切都是由basketid組織。具有最早fruit.received日期的basketid首先出現,然後其他行按照日期asc相同的basketid,然後是具有下一個最早的fruit.received日期的basketid,接着是具有相同的basketid的其他行,依此類推。

所以輸出應該是這樣的:

 
Fruitid | Received | Basket 
    4  20091129  Premuim Fruit 
    1  20100310  Premuim Fruit 
    2  20091205  Standard Produce 
    3  20100220  Big Discounts 

任何想法如何在一個單一的執行做到這一點?

回答

2

試試這個(SQL Server表設置代碼,但查詢應在任何數據庫工作)

DECLARE @Fruit table (fruitid int, received int, basketid int) 
INSERT @Fruit VALUES(1,  20100310, 2) 
INSERT @Fruit VALUES(2,  20091205, 3) 
INSERT @Fruit VALUES(3,  20100220, 1) 
INSERT @Fruit VALUES(4,  20091129, 2) 

DECLARE @Basket table (id int,basket varchar(20)) 
INSERT @Basket VALUES (1, 'Big Discounts' ) 
INSERT @Basket VALUES (2, 'Premium Fruit' ) 
INSERT @Basket VALUES (3, 'Standard Produce') 


SELECT 
    f.Fruitid ,f.received,b.basket 
    FROM @Fruit f 
     INNER JOIN (SELECT 
         basketid, MIN(received) AS received 
         FROM @Fruit 
         GROUP BY basketid 
       ) o ON f.basketid = o.basketid 
     INNER JOIN @Basket b ON o.basketid=b.id 
    ORDER BY o.received 

輸出

Fruitid  received basket 
----------- ----------- -------------------- 
4   20091129 Premium Fruit 
1   20100310 Premium Fruit 
2   20091205 Standard Produce 
3   20100220 Big Discounts 

(4 row(s) affected) 
+0

認爲你應該將ORDER BY更改爲ORDER BY o.received,f.received – sgmoore 2010-03-26 15:40:40

+0

@sgmoore,是的,我發現在@Quassnoi將它添加到他的查詢後 – 2010-03-26 16:08:07

2
SELECT f.fruitid, f.received, ba.name AS basket 
FROM Fruit f 
JOIN (
     SELECT basketid, MIN(received) AS mr 
     FROM fruit 
     GROUP BY 
       basketid 
     ) b 
ON  f.basketid = b.basketid 
JOIN basket ba 
ON  ba.id = f.basketid 
ORDER BY 
     b.mr, f.basketid, f.received 
+0

這並沒有給該OP希望 – 2010-03-26 15:18:52

+0

列@ KM:現在確實,而不是因爲我的編輯。 – 2010-03-26 15:34:03

+0

沒有'f.mr'命令應該是b.mr; '來自Friut'應該水果; 'ON f.backetid'應該是f.basketid; ',ba.name'應該是ba.basket – 2010-03-26 15:34:24