复杂的订单条款?

时间:2010-03-26 15:06:09

标签: sql sql-server sql-order-by

我需要对我做什么是高级排序。我有这两个表:

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.ceceived日期的basketid首先出现,然后是具有相同basketid的日期asc的其他行,然后是具有下一个最早的fruit.ceceived日期的basketid,接着是具有相同basketid的其他行,依此类推。

所以输出看起来像这样:

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

任何想法如何在一次执行中完成此任务?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)
相关问题