access数据库中的sql排序

oxcyiej7  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(590)

我试图在access中对数据库进行排序,但我做不到。我只需要用最近一天的记录。先是价格最低的城市和该城市的所有价格,然后是价格第二低的城市,等等。谢谢!!
这是示例数据库:

Date           Country    City     Price    Departure_date     Return_date
05-06-2019     Peru       Lima     360$     xxxx               xxxxx
05-06-2019     Peru       Lima     420$     xxxx               xxxxx
05-06-2019     Mexico     CMX      300$     xxxx               xxxxx
05-06-2019     Mexico     CMX      400$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019     Peru       Cusco    50$      xxxx               xxxxx
05-06-2019     Peru       Cusco    60$      xxxx               xxxxx
04-06-2017     Mexico     Cancun   300$     xxxx               xxxxx
04-06-2017     Peru       Cusco    70$      xxxx               xxxxx
04-06-2017     Peru       Cusco    30$      xxxx               xxxxx

必须这样分类:

Date         Country    City     Price    Departure_date     Return_date
05-06-2019   Peru       Cusco    50$      xxxx               xxxxx
05-06-2019   Peru       Cusco    60$      xxxx               xxxxx
05-06-2019   Mexico     CMX      300$     xxxx               xxxxx
05-06-2019   Mexico     CMX      400$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019   Peru       Lima     360$     xxxx               xxxxx
05-06-2019   Peru       Lima     420$     xxxx               xxxxx
bprjcwpo

bprjcwpo1#

可能有一种方法可以将其浓缩,但应根据需要执行以下操作:

select t0.*
from 
    YourTable t0 inner join
    (
        select t1.city, t1.date, min(t1.price) as mprice
        from 
            YourTable t1 inner join
            (
                select t2.city, max(t2.date) as mdate
                from YourTable t2
                group by t2.city
            ) t3 
            on t1.date = t3.mdate and t1.city = t3.city
        group by 
            t1.city, t1.date
    ) t4 
    on t0.city = t4.city and t0.date = t4.date
order by 
    t4.mprice, t0.city, t0.price

基本上:
最里面的子查询( t3 )获取每个城市最新日期的记录( mdate ).
外部子查询( t4 )获得最低价格( mprice )在每个城市的最新记录中。
最后,主查询输出相关记录,按最低价格排序(对城市组进行排序),然后按 city (以相同的最小值对城市进行排序),然后按 price 对每个城市组内的记录进行排序。
您将需要更改 YourTable 到您的表名。

相关问题