http://www.cnblogs.com/sumsen/archive/2012/05/30/2525800.html
实例(每个分组第一条记录):
获取每个分组(以DT.S_ACCNO,"SUBSTR"(DT.S_ACCDATE,1,6)分组),以DT.S_ACCNO,DT.S_ACCDATE 为倒序的排名第一的记录
SELECT dt.KJKMDM,dt.S_TRECODE,dt.S_ACCNO,dt.N_MONEYTODAY,dt.S_ACCDATE,DF.GKJB FROM (SELECT DM.KJKMDM,TI.S_TRECODE,TI.S_ACCNO,TI.N_MONEYTODAY,TI.S_ACCDATE,RANK() OVER (partition by TI.S_ACCNO,"SUBSTR"(TI.S_ACCDATE,6) ORDER BY TI.S_ACCNO,TI.S_ACCDATE DESC) AS rn FROM TIPS_LIB_INVENTORY_DAILY ti LEFT JOIN DM_ACCOUNT dm ON DM.KJZH = TI.S_ACCNO) dt LEFT JOIN DM_FISC df ON DT.S_TRECODE = DF.GKDM WHERE rn=1
rank()排序函数根据partition by DT.S_ACCNO,6) 分组,根据order by DT.S_ACCNO,DT.S_ACCDATE desc再排序
另一种方法取每个分组中的第一
SELECT dt.KJKMDM,TI.S_TRECODE FROM (select t.s_accdate,t.s_accno,t.n_moneytoday,t.S_TRECODE from tips_lib_inventory_daily t inner join (select substr(t.s_accdate,6) as month,[color=red]max(t.s_accdate)as s_accdate[/color],t.s_accno from tips_lib_inventory_daily t [color=red]group by substr(t.s_accdate,6),t.s_accno) b on t.s_accdate = b.s_accdate and t.s_accno = b.s_accno) ti LEFT JOIN DM_ACCOUNT dm ON DM.KJZH = TI.S_ACCNO ) dt LEFT JOIN DM_FISC df ON DT.S_TRECODE = DF.GKDM ORDER BY DT.S_ACCNO,DT.S_ACCDATE这种思想是,先求分组中的最大max(t.s_accdate)然后再去inner join取与最大值相等的记录 第二种方法速度更快,剔除了不必要的记录,第一种要对所有排序,再去每个分组的第一条记录