按表里的id分组查询每个id的前十条收入字段的和(按最近日期的前十条),求解解决方法
按表里的id分组查询每个id的前十条收入字段的和(按最近日期的前十条),求解
如题:求一条查询语句:
按表里的id分组查询每个id的前十条收入字段的和(按最近日期的前十条),求解
------解决方案--------------------
SELECT * from tt a1 where (select count(*) from a where a1.id=id and a1.date<=date)<=10
------解决方案--------------------
如果支持ROW_NUMBER,更简单
select * from (
select *,ROW_NUMBER() over(partition by id order by date desc) as pm from tt) a
where pm<=10
------解决方案--------------------
如题:求一条查询语句:
按表里的id分组查询每个id的前十条收入字段的和(按最近日期的前十条),求解
------解决方案--------------------
SELECT * from tt a1 where (select count(*) from a where a1.id=id and a1.date<=date)<=10
------解决方案--------------------
如果支持ROW_NUMBER,更简单
select * from (
select *,ROW_NUMBER() over(partition by id order by date desc) as pm from tt) a
where pm<=10
------解决方案--------------------
- SQL code
select * from ( select *,ROW_NUMBER() over(partition by id order by date desc) as rn from table ) a where rn<=10
------解决方案--------------------
参考下贴中的多种方法
http://topic.****.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
[征集]分组取最大N条记录方法征集,及散分....
------解决方案--------------------
- SQL code
SELECT * from 表 t where 10>(select count(*) from 表 where id=t.id and 日期>t.日期)
------解决方案--------------------
db2中可以用ROW_NUMBER() over(partition by 。。。)来做。
------解决方案--------------------
create table emp(id integer,salary decimal(10,2),thedate date);
select id,sum(salary) from (select id,salary,thedate,row_number()over(partition by dept order by thedate desc) as rw from emp) where rw<=10 group by id
请楼主给分,不好用的话我还你双倍的分。