group by 如何与Max()连用比如有一个表姓名 订单 订单金额 订单名称 ..........
张三 3 500 订单3 ..........
张三 5 100 订单5
李四 14 4000 订单14
王五 54 6000 订单54
李四 23 3000 订单23
我现在想查询表中每个人订单金额最大的那行数据的值,该如何写SQL语句?能通过 group by ,和having 实现么?
张三 3 500 订单3 ..........
张三 5 100 订单5
李四 14 4000 订单14
王五 54 6000 订单54
李四 23 3000 订单23
我现在想查询表中每个人订单金额最大的那行数据的值,该如何写SQL语句?能通过 group by ,和having 实现么?
where not exists(select 1 from tb where 姓名=t.姓名 and 订单金额>t.订单金额)
from tb t
where not exists(select 1 from tb where 姓名=t.姓名 and 订单金额>t.订单金额)
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 行受影响)
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 行)
*
from
tb t
where
订单金额=(select max(订单金额) from tb where 姓名=t.姓名)
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 行受影响)
*/
where 表.姓名=表2.姓名 and 表.订单金额=表2.金额