group by 如何与Max()连用比如有一个表姓名       订单      订单金额      订单名称 ..........
张三        3          500          订单3   ..........
张三        5          100          订单5
李四        14         4000         订单14
王五        54         6000         订单54
李四        23         3000         订单23
我现在想查询表中每个人订单金额最大的那行数据的值,该如何写SQL语句?能通过 group by ,和having 实现么?

解决方案 »

  1.   

    select * from tb t
    where not exists(select 1 from tb where 姓名=t.姓名 and 订单金额>t.订单金额)
      

  2.   

    select *
    from tb t
    where not exists(select 1 from tb where 姓名=t.姓名 and 订单金额>t.订单金额)
      

  3.   

    --> 测试数据: @tb
    declare @tb table (姓名 varchar(4),订单 int,订单金额 int,订单名称 varchar(6))
    insert into @tb
    select '张三',3,500,'订单3' union all
    select '张三',5,100,'订单5' union all
    select '李四',14,4000,'订单14' union all
    select '王五',54,6000,'订单54' union all
    select '李四',23,3000,'订单23'select * from @tb t
    where not exists(select * from @tb where 姓名=t.姓名 and 订单金额>t.订单金额)
    姓名   订单          订单金额        订单名称
    ---- ----------- ----------- ------
    张三   3           500         订单3
    李四   14          4000        订单14
    王五   54          6000        订单54(3 行受影响)
      

  4.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([姓名] varchar(4),[订单] int,[订单金额] int,[订单名称] varchar(6))
    insert [tb]
    select '张三',3,500,'订单3' union all
    select '张三',5,100,'订单5' union all
    select '李四',14,4000,'订单14' union all
    select '王五',54,6000,'订单54' union all
    select '李四',23,3000,'订单23'
     
    ---查询---
    select *
    from tb t
    where not exists(select 1 from tb where 姓名=t.姓名 and 订单金额>t.订单金额)
    ---结果---
    姓名   订单          订单金额        订单名称   
    ---- ----------- ----------- ------ 
    张三   3           500         订单3
    李四   14          4000        订单14
    王五   54          6000        订单54(所影响的行数为 3 行)
      

  5.   

    select 
     *
    from
     tb t
    where
     订单金额=(select max(订单金额) from tb where 姓名=t.姓名)
      

  6.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([姓名] varchar(4),[订单] int,[订单金额] int,[订单名称] varchar(6))
    insert [tb]
    select '张三',3,500,'订单3' union all
    select '张三',5,100,'订单5' union all
    select '李四',14,4000,'订单14' union all
    select '王五',54,6000,'订单54' union all
    select '李四',23,3000,'订单23'select 
     *
    from
     tb t
    where
     订单金额=(select max(订单金额) from tb where 姓名=t.姓名)
    /*姓名   订单          订单金额        订单名称
    ---- ----------- ----------- ------
    张三   3           500         订单3
    王五   54          6000        订单54
    李四   14          4000        订单14(3 行受影响)
    */
      

  7.   

    http://topic.csdn.net/u/20080626/00/43d0d10c-28f1-418d-a05b-663880da278a.html?73339
      

  8.   

    可以啊,select * from 表,(select 姓名,max(订单金额) as 金额 from 表 group by 姓名) 表2
    where 表.姓名=表2.姓名 and 表.订单金额=表2.金额