mybatis先排序後分組

2021-09-26 13:06:26 字數 1006 閱讀 5860

1. 乙個統計資料的需求是取每個月資料,並展示當月的總值;因為展示該月總值的話,需要展示該月中記錄時間最大的作為展示;故先要進行排序後再分組;

select if(sd.tx_type=1, sum(sd.tx_vb), 0) as txvb,

if(sd.tx_type=0, sum(sd.tx_vb), 0) as outvb,

sd.after_vb, sd.create_time

from ( select * from t_score_detail order by create_time desc ) as sd

join t_score s on sd.score_id = s.score_id

where s.user_id = #

and sd.source = 6

group by date_format(sd.create_time,'%y%m')

2. 但是以上並沒有出現預期的分組後的資料是每月時間最大的那條資料。

有建議稱,在先排序中進行limit,經測試,結果能達到預期效果。

select if(sd.tx_type=1, sum(sd.tx_vb), 0) as txvb,

if(sd.tx_type=0, sum(sd.tx_vb), 0) as outvb,

sd.after_vb, sd.create_time

from ( select * from t_score_detail where user_id = # and and source = 6 order by create_time desc limit 999 ) as sd

join t_score s on sd.score_id = s.score_id

where 1 = 1

group by date_format(sd.create_time,'%y%m')

3. 有關人士指出需要注意的是:如果對要排序的字段如果存在重複值,則會導致排序失效。

MySql下實現先排序後分組

最近在工作中遇到乙個先排序後分組的需求,發現mysql不同的版本有不同的結果,特此記錄。舉例 要求在shop表中查詢出各型別商店中 最高的商品。表結構 create table shop id int 10 primary key,shop name varchar 100 item name va...

mysql先排序後分組方法

直接上sql select c.from select a.id,a.longitude,a.latitude,b.state,b.id as bid from event t room info a left join event.t active b on a.id b.room id and ...

mysql 先排序再分組的sql語句實現

最近專案中有乙個需求,需要先分組,再排序的功能。搞了好久,經過敏大大 後台兄弟 指導,終於搞出來了,分享給大家 demo 學生資訊表 第一時間想到 sql select from t test group by name,type order by score desc 結果 發現,並不能滿足我們需...