mysql 分组内 排序 类似于 sqlserver over partition by
因为mysql中木有sqlserver over partition by这个函数,要从sqlserver 中把查询迁到mysql ,遇到了一些问题,暂时是这样解决的
select id, CreationTime, Sku from product_picture
返回结果:
1.同组SKU 给createTime排序
2.同组SKU
定义变量后循环赋值:
SELECT id, rank, rank2, CreationTime, Sku FROM ( SELECT *, @rownum := @rownum + 1, IF ( @pdept = heyf_tmp.Sku, @rank := @rank + 1, @rank := 1 ) AS rank, @pdept := heyf_tmp.Sku, IF ( @pdept2 != heyf_tmp.Sku, @rownum2 := @rownum2 + 1, @rownum2 ) AS rank2, @pdept2 := heyf_tmp.Sku FROM ( -- 只需要改此括号中内容 SELECT * FROM product_picture ORDER BY Sku ASC, CreationTime DESC ) heyf_tmp, ( SELECT @rownum := 0, @pdept := NULL, @rank := 0 ) a , ( SELECT @rownum2 := 1, @pdept2 := NULL) b ) result;
返回结果:
rank :表示同组sku下的createtime排序结果
rank1:表示同组sku