有这样一个数据表id(主键)   city1(出发城市)  city2(到达城市)   price(从city1到city2的所需价格)有以下数据:1   上海 北京 900
2   上海 北京 914
3   上海 北京 372
4   上海 青岛 689
5   上海 成都 523
6   上海 成都 781
7   上海 青岛 88
8   上海 青岛 989
9   上海 重庆 187
10  上海 杭州 382
11  上海 重庆 228
12  上海 杭州 508
13  上海 杭州 688
14  上海 重庆 1228
15  上海 重庆 28
......
......求查询从 上海 到 其他 各地 的最低的前2个价格...例如
3   上海 北京 372
1   上海 北京 900  
7   上海 青岛 88
4   上海 青岛 689
15  上海 重庆 28
9   上海 重庆 187
....
....
....

解决方案 »

  1.   

    select a.id,a.city1,a.city2
    from tt a left join tt b
    on a.city1=b.city1 and a.price>=b.price
    group by a.id,a.city1,a.city2
    having count(b.id)<=2
      

  2.   

    参考下贴中的多种方法http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
    [征集]分组取最大N条记录方法征集,及散分....
      

  3.   

    select * 
    from 有这样一个数据表 a
    where 2>(select count(*) from 有这样一个数据表 where city1=a.city1 and city2=a.city2 and price<a.price)
      

  4.   

    or
    select a.* from tt a where 2<=(select count(*) from tt 
    where a.city1=city1 and a.city2=city2 and a.price>=price)
      

  5.   

    select a.id,a.city1,a.city2
    from tt a left join tt b
    on a.city1=b.city1 and a.city2=b.city2 and a.price>=b.price
    group by a.id,a.city1,a.city2
    having count(b.id)<=2
      

  6.   


    我试了下
    having count(b.id)<=2 这样不行啊,这样是取出 “满足 b.id 的总数小于2的”;
    并不是只取出2个。
      

  7.   

    select a.id,a.city1,a.city2,a.price
    from tty1 a left join tty1 b
    on a.city1=b.city1 and a.city2=b.city2 and a.price>=b.price
    group by a.id,a.city1,a.city2,a.price
    having count(b.id)<=2
    order by a.city1,a.city2,a.price 少写了PRICE
      

  8.   


    一样的啊,并不能取出每一组的前两个;而是 取出每一组的 count(b.id)<=2 的那些组。。having count(b.id)<=2  这个我试了下,好像并不是说只取出两个, 而是说 每组count(b.id)要 <=2 。例如:1 上海 北京 900
    2 上海 北京 914
    3 上海 北京 372
    4 上海 青岛 689
    5 上海 成都 523
    6 上海 成都 781

    7 上海 青岛 88
    8 上海 青岛 989
    9 上海 重庆 187
    10 上海 杭州 382
    11 上海 重庆 228
    12 上海 杭州 508
    13 上海 杭州 688
    14 上海 重庆 1228
    15 上海 重庆 28
    ......
    ......
    上面好像就只有红色的成都才满足了  count(b.id)<=2 ; 其他的都 > 2了。
      

  9.   

    我是希望每一组取出价格最少的那两个。例如:3 上海 北京 372
    1 上海 北京 900  
    7 上海 青岛 88
    4 上海 青岛 689
    15 上海 重庆 28
    9 上海 重庆 187
    ......

    但是用count(b.id)<=2,是只能取出总数小于或等于2的,例如:
    5 上海 成都 523
    6 上海 成都 781
      

  10.   

     #3楼 的你试了吗?如果仍不行,建议提供测试数据
     (不要高估你的汉语表达能力或者我的汉语理解能力)
       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。