急求SQL查询方法
下面是一张表里的数据,我需要按A分组查询,每组中取出max(B),及与B对应的sum(C)
A B C
2007-1-1 1001 100
2007-1-1 1001 100
2007-1-1 1002 200
2007-1-1 1002 200
2007-1-1 1003 300
2007-1-1 1003 300
2007-2-1 2001 100
2007-2-1 2002 200
2007-2-1 2002 200
应该怎么查啊?我没辙了!拜托各位,给个解决办法!
------解决方案--------------------select a,max(b),sum(c) from test group by a
----------------------------------
要看你的A 是什么类型的若是日期型的要这样:
select to_char(a, 'yyyy-mm-dd '),max(b),sum(c) from test group by to_char(a, 'yyyy-mm-dd ');
不明白的地方:
什么叫做与B对应的SUM(C)呀
------解决方案--------------------select a,sum(c) from tablename aa where b=(select max(b) from tablename where a=aa.a) group by a
------解决方案--------------------select to_char(a, 'yyyy-mm-dd ') ,b,sum(c) from tablename t,(select to_char(a, 'yyyy-mm-dd ') m_a,max(b) m_b from tablename group by to_char(a, 'yyyy-mm-dd ')) m
where t.to_char(a, 'yyyy-mm-dd ') = m.m_a and t.b=m.b
group by to_char(a, 'yyyy-mm-dd '),b
没有测试过 自己测试下
------解决方案--------------------select a,maxb,sumc
from(
select a,b,c
,max(b)over(partition by a) maxb
,sum(c)over(partition by a,b) sumc
,row_number()over(partition by a,b order by b) rn
from mmtb
)
where b=maxb
and rn=1
接分!