复杂的ORDER BY子句?

问题描述 投票:2回答: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至上,然后与日递增,那么下一个最早fruit.received日期,然后用同样的basketid其他行的basketid,所以在相同的basketid其他行。

所以输出应该是这样的:

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

任何想法如何在一个单一的执行做到这一点?

sql sql-server sql-order-by
2个回答
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

OUTPUT

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

(4 row(s) affected)

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
© www.soinside.com 2019 - 2024. All rights reserved.