我有一个数据表 A表,结构和数据如下aid     atitle   bid
1       苹果     1
2       离子     1
3       橡胶     2
4       葡萄     1其中bid是另外一个表的主键这里我想读出一组数据,这数据中,满足下面的条件
条件1.每个bid的只能读出一条,这样满足条件的是
aid 为 1,2,3,4,但其中 1,2,4只能显示一条
条件2.相同bid的,读出的是aid最大的那条
然后这样得到的数据是aid     atitle   bid
3       橡胶     2
4       葡萄     1并且最后的排序按照 bid 的降序排列,请问这个SQL语句该怎么写呢?

解决方案 »

  1.   

    条件不足啊,你要给出一个atitle的过滤条件
    select aid,atitle,bid from A where aid in
    (select MAX(aid) AS aid from A group by bid) 
      

  2.   

    这样
    select * from table1 where aid in(Select max(aid) FROM table1 group by bid) order by bid desc
      

  3.   


    select * from table1 a not exists
    (select * from table1 where bid=a.bid and aid<a.aid)
    order by bid desc
      

  4.   

    DECLARE @TB TABLE(aid INT,   atitle  VARCHAR(10),bid INT)
    INSERT @TB
    SELECT 1  ,    '苹果'  ,  1 UNION
    SELECT 2  ,    '离子'  ,  1 UNION
    SELECT 3  ,    '橡胶'  ,  2 UNION
    SELECT 4  ,    '葡萄'  ,  1 SELECT * FROM @TB T WHERE AID=(SELECT MAX(AID) FROM @TB WHERE BID=T.BID) ORDER BY BID DESCSELECT * FROM @TB T WHERE NOT EXISTS(SELECT 1 FROM @TB WHERE BID=T.BID AND AID>T.AID)
    (所影响的行数为 4 行)aid         atitle     bid         
    ----------- ---------- ----------- 
    3           橡胶         2
    4           葡萄         1(所影响的行数为 2 行)aid         atitle     bid         
    ----------- ---------- ----------- 
    3           橡胶         2
    4           葡萄         1(所影响的行数为 2 行)
      

  5.   

    select a.* from tb a where aid= (select max(aid) from tb where atitle = a.atitle  ) order by a.bidselect a.* from tb a where not exists(select 1 from tb where atitle= a.atitle and aid> a.aid)
      

  6.   

    看看我的语句select aid, atitle, bid from A where aid in (select max(aid) as max_aid from A group by bid) order by bid desc执行结果在查询分析器中试过了,结果跟你要的一样。思路:
    1.相同bid的,你只能要一条记录,且只要最大的那一条,所以必须按bid来分组(group by bid)
    2.在相同bid的情况,你要的是aid最大的那条,所以用max(aid),这样就挑出了所有要的数据了。
    3。只因你还要其他字段的数据,所以得从原表中去寻找,把与max(aid)对应的那条挑选出来。
      

  7.   

    向*学习,你们太牛了,SQL还要学习
      

  8.   

    sql高手如此之多,让我感觉压力好大啊
      

  9.   

    还有种写法,不过烦了点
    SELECT     a.bid, a.aid, b.atitle
    FROM         (SELECT DISTINCT bid, MAX(aid) AS aid
                           FROM          Table_1
                           GROUP BY bid) AS a LEFT OUTER JOIN
                              (SELECT     aid, atitle, bid
                                FROM          Table_1 AS Table_1_1) AS b ON a.bid = b.bid AND a.aid = b.aid