group by分组查询小结

1.按某一字段分组后查询某一条件下的所有数据:如下面的按照ReservePhone:手机号分组后,再查询是特定的手机号的所有数据

select ID , GroupCode,HotelCode,AccountNo,ReservePhone,ReserveName,RoomNo,RoomType from Res_RoomResource 
where ID in (select (ID) from Res_RoomResource where GroupCode='0001' and hotelcode='021002' group by  ReservePhone,ID) 
and ReservePhone='18537*****';

下面这样查的话只能查询到一条记录
select ID , GroupCode,HotelCode,AccountNo,ReservePhone,ReserveName,RoomNo,RoomType from Res_RoomResource 
where ID in (select min(ID) from Res_RoomResource where GroupCode='0001' and hotelcode='021002' group by  ReservePhone,ID) 
and ReservePhone='18537693630';--min(ID) 或者Max(ID)

补充:

1.对于表TA中存在主键id,所以可利用主键id来查询:

select ID , CODE , VALUE ,  DESC  , DATE form TA where ID in (select min(ID) from TA group by CODE , VALUE) ;

2.对于表TB中,表不存在主键,则查询方式为:

select min(ID) ID, CODE , VALUE ,  min(DESC) DESC ,min( DATE) DATE  from TA group by CODE , VALUE ;

总结:

方式1一般都适用 于单表的查询,因为一般建表的时候都会建主键;对于视图,联查的时候,方式一可能就不合适了,就可以用方式2

猜你喜欢

转载自www.cnblogs.com/newcapecjmc/p/12175648.html