http://www.cnblogs.com/sumsen/archive/2012/05/30/2525800.html
instance (each Group the first record):
Get each group (grouped by DT.S_ACCNO,"SUBSTR"(DT.S_ACCDATE,1,6)), with DT.S_ACCNO,DT.S_ACCDATE as the first record in reverse order
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,1,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
The rank() sorting function is grouped according to partition by DT.S_ACCNO,"SUBSTR"(DT.S_ACCDATE,1,6), and reordered according to order by DT.S_ACCNO,DT.S_ACCDATE desc
Another method takes the first one
SELECT dt.KJKMDM,dt.S_TRECODE,dt.S_ACCNO,dt.N_MONEYTODAY ,dt.S_ACCDATE, DF.GKJB FROM (SELECT DM.KJKMDM,TI.S_ACCNO,TI.N_MONEYTODAY ,TI.S_ACCDATE,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,1,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,1,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
The idea is to first find the maximum max (t.s_accdate) in the group, and then go to the inner join to get the record equal to the maximum value. The
second method is faster and eliminates unnecessary records. Sort, then go to the first record of each group