多表使用分组Group By
两个表,分别为表A和表B,A是分类表,B是产品详细表,结构和数据如下:
A
a_id,a_name
1 苹果
2 橘子
3 香蕉
B
b_id,b_name,b_num,a_id
1 苹果一 10 1
2 苹果二 20 1
3 橘 子 30 2
4 香蕉一 40 3
5 香蕉二 50 3
求解:查询出各分类,点击次数(b_num)最多的产品信息,结果数据应为:
1 苹果二 20
3 橘 子 30
3 香蕉二 50
[解决办法]
--> 测试数据:[tbla]if object_id('[tbla]') is not null drop table [tbla]create table [tbla]([a_id] int,[a_name] varchar(4))insert [tbla]select 1,'苹果' union allselect 2,'橘子' union allselect 3,'香蕉'--> 测试数据:[tblb]if object_id('[tblb]') is not null drop table [tblb]create table [tblb]([b_id] int,[b_name] varchar(6),[b_num] int,[a_id] int)insert [tblb]select 1,'苹果一',10,1 union allselect 2,'苹果二',20,1 union allselect 3,'橘子',30,2 union allselect 4,'香蕉一',40,3 union allselect 5,'香蕉二',50,3select d.[b_id],e.* from(select [a_name],MAX([b_num]) [b_num] from(select b.[b_id],a.[a_name],b.[b_num] from tblb bfull join tbla a on a.a_id=b.a_id)cgroup by [a_name])e inner join (select b.[b_id],a.[a_name],b.[b_num] from tblb bfull join tbla a on a.a_id=b.a_id)d on d.a_name=e.a_name and d.b_num=e.b_num/*b_id a_name b_num2 苹果 203 橘子 305 香蕉 50*/
[解决办法]
这个问题我有点质疑,如果苹果一和苹果二的价格都是20,而20都是最高价,结果会怎么样
2楼的结果看来,好像不用这么复杂的语句吧
select a.a_id, a.a_name, max(b.b_sum)from tbla a inner join tblb b on a.a_id = b.a_idgroup by a.a_id, a.a_nameorder by a.a_id
[解决办法]
select * from 产品详细表 a where not exists(select * from 产品详细表 b where a.a_id =b.a_id and a.b_num <b.b_num )
[解决办法]
select * from b b1 not exists
(
select 1 from b b2 where b1.a_id=b2.a_id and b1.b_num<b2.b_num
)