oracle SQL 取出每个分组的按照日期最新一条记录,同时还显示每个分组某个字段的总和
如:tabletestcodenumpricedatea110.002014-04-01a220.002014-04-02a330.002014-04-03b220.00...
如:table test
code num price date
a 1 10.00 2014-04-01
a 2 20.00 2014-04-02
a 3 30.00 2014-04-03
b 2 20.00 2014-04-07
b 1 10.00 2014-04-03
b 5 22.00 2014-04-01
以code 字段分组,并取每个分组日期最新的一条记录以及每个分组num字段的值的总和
结果:
code num price date SUM(num)
a 3 30.00 2014-04-03 6
b 2 20.00 2014-04-07 8 展开
code num price date
a 1 10.00 2014-04-01
a 2 20.00 2014-04-02
a 3 30.00 2014-04-03
b 2 20.00 2014-04-07
b 1 10.00 2014-04-03
b 5 22.00 2014-04-01
以code 字段分组,并取每个分组日期最新的一条记录以及每个分组num字段的值的总和
结果:
code num price date SUM(num)
a 3 30.00 2014-04-03 6
b 2 20.00 2014-04-07 8 展开
展开全部
--用外链接把AA表和CC表链接起来查询就可以了
SELECT AA.CODE, AA.NUM, AA.PRICE, CC.DATETIME, CC.SUMNUM
FROM test AA
--下面的BB表查询的是根据code分组查询num求和及最大datetime,之后作为一个表CC
LEFT JOIN (SELECT BB.CODE, SUM(NUM) SUMNUM,MAX(BB.DATETIME) DATETIME
FROM test BB
GROUP BY BB.CODE) CC
ON AA.CODE = CC.CODE
WHERE AA.DATETIME = CC.DATETIME
--其中DATETIME字段就是你表中的date字段
展开全部
select code,num,price,date,sum_num
from (
select code,num,price,date,row_number() over (partition by code order by date desc) rn,
sum(num) over (partition by code) sum_num
from table_name --这一行之前没加,引起误会,抱歉..
) a
where rn=1
from (
select code,num,price,date,row_number() over (partition by code order by date desc) rn,
sum(num) over (partition by code) sum_num
from table_name --这一行之前没加,引起误会,抱歉..
) a
where rn=1
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
使用组函数SQL和表连接来实现,代码如下:
select aa.*,bb.sumnum from (select * from test where (code,date) in (select code,max(date) from test group by code)) as aa join (select code,sum(num) as sumnum from test group by code) as bb on aa.code==bb.code
select aa.*,bb.sumnum from (select * from test where (code,date) in (select code,max(date) from test group by code)) as aa join (select code,sum(num) as sumnum from test group by code) as bb on aa.code==bb.code
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select a.code,a.num,a.price,a.date1,b.sum1
from test a,(select code,max(date1) date1,sum(num) sum1 from test group by code) b
where a.code=b.code and a.date1=b.date1
;
code和date做为组合关键字必需唯一,否则没法实现你目前的需求
from test a,(select code,max(date1) date1,sum(num) sum1 from test group by code) b
where a.code=b.code and a.date1=b.date1
;
code和date做为组合关键字必需唯一,否则没法实现你目前的需求
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询