一、场景:
表statistics_test
a_id money in_time
1 20 2015-11-12
1 10 2015-11-13
2 4 2015-10-09
2 36 2015-10-10
将该表的数据,以id统计金额的总数,记录的数量,并显示出最大日期的记录
即输出:
a_id in_time count sum_money
1 2015-11-13 2 30
2 2014-10-10 2 40
二、问题解决
该问题的解决分为三步:
(1)先按id进行统计,采用group by ,输出a_id,count,sum_money作为一张表P;
select a_id,sum(money),count(a_id) from statistics_test group by a_id; 注意使用了group by子句后,select后面的字段只能是group by后出现的字段,之外的字段已聚集函数的形式,出现在select后面,select出来的结果集可以作为一张表,与oracle库中的表进行连接;
(2)将表P与表statistics_test进行关联,输出时间字段;
(3)最后按a_id找出日期最大的记录。
找日期最大的采用的单表自身关联,借助于max函数来实现
如下:
SELECT a.a_id,a.in_time,P.cou,P.mon FROM statistics_test a,(select a_id,count(a_id) as cou,sum(money) as mon from statistics_test Group By A_ID) P where a.a_id = P.a_id and a.in_time =(select max(a1.in_time) from statistics_test a1 where a.a_id = a1.a_id);
总结:
(1)对group by的使用方法;
(2) select 后的结果集可以与数据表进行等值连接;
(3) 按重复字段找日期最大的记录的方法(按重复字段自身连接);