1.oracle开展分组后,取出每组的前几条数据:
oracle进行分组后,取出每组的前几条数据SELECT *FROM (SELECT 分组的字段名,
ROW_NUMBER() OVER(PARTITION BY 分组的字段名 ORDER BY 排序的字段名) AS RNFROM 表名)WHERE RN <= 10
例:表mfsysevent按SKUNO分组再按SCANDATETIME排序,然后取出每个SKUNO的前十位
SELECT *FROM (SELECT SKUNO,SYSSERIALNO,
ROW_NUMBER() OVER(PARTITION BY SKUNO ORDER BY SCANDATETIME DESC) AS RN FROM MFSYSEVENT where SKUNO IN('68-4554-06','68-100328-03')
)WHERE RN <= 10
2.利用SQL语句每天都统计前面几天的总额
原始表TTT如图示
SELECT *FROM TTT
方法一:
select ROWNUM,ID, NUM, (select sum(NUM) from TTT B where B.id<=TTT.id) from TTT
方法二:
select A.ID, sum(B.NUM) from TTT A join TTT B on A.id>=B.id group by A.id
方法三(推荐):
SELECT ID,NUM,SUM(NUM) OVER(ORDER BY NUM)FROM TTT
对比三个方法可以看出,只有方法三没有用栏位ID作为查询条件,在没有ID的情况下依然可用。