数据库结构如下:
Date FirmID ClassID Qty HoldQty
日期 会员号 品种 成交量 持有量
2006-8-1 001 WS 200 300
2006-8-5 001 WS 100 200
2006-8-9 001 WS 50 150
......
现在我想查出8.1-8.5,所有会员各个品种的成交量(累加)和持有量(时间段内最后一天的数据),
结果应该是:
FirmID ClassID Qty HoldQty
001 WS 350 150
001 CF .. ..============================
因为库里每天都会有几十万条记录,请大家给一个尽量简洁高效的语句,谢谢。
---------------------------------------
我现在写的语句如下,总感觉不够简洁高效。
select t1.FirmID,t1.ClassID,t1.Qty,t2.HoldQty
from (select FirmID,ClassID,sum(Qty) as Qty
from table
where date1<=Date<=date2
group by FirmID,ClassID) T1,
(select FirmID,ClassID,HoldQty
from table
where (Date,FirmID,ClassID) IN
(select max(Date) as Date,FirmID,ClassID from table
where date1<=Date<=date2
group by FirmID,ClassID)) T2
where t1.FirmID=t2.FirmID and t1.ClassID=t2.ClassID
Date FirmID ClassID Qty HoldQty
日期 会员号 品种 成交量 持有量
2006-8-1 001 WS 200 300
2006-8-5 001 WS 100 200
2006-8-9 001 WS 50 150
......
现在我想查出8.1-8.5,所有会员各个品种的成交量(累加)和持有量(时间段内最后一天的数据),
结果应该是:
FirmID ClassID Qty HoldQty
001 WS 350 150
001 CF .. ..============================
因为库里每天都会有几十万条记录,请大家给一个尽量简洁高效的语句,谢谢。
---------------------------------------
我现在写的语句如下,总感觉不够简洁高效。
select t1.FirmID,t1.ClassID,t1.Qty,t2.HoldQty
from (select FirmID,ClassID,sum(Qty) as Qty
from table
where date1<=Date<=date2
group by FirmID,ClassID) T1,
(select FirmID,ClassID,HoldQty
from table
where (Date,FirmID,ClassID) IN
(select max(Date) as Date,FirmID,ClassID from table
where date1<=Date<=date2
group by FirmID,ClassID)) T2
where t1.FirmID=t2.FirmID and t1.ClassID=t2.ClassID
select T1.FirmID,T1.ClassID,T1.Qty,T2.HoldQty
(
select FirmID,ClassID,sum(Qty) as Qty,max(Date) date
from table
where date1<=Date<=date2
group by FirmID,ClassID
) T1,
table T2
where T1.FirmID=T2.FirmID and T1.ClassID=T2.ClassID and T1.date=T2.Date
你的要求和希望得到的结果不一致啊!
--------------
数据库结构如下:
Date FirmID ClassID Qty HoldQty
日期 会员号 品种 成交量 持有量
2006-8-1 001 WS 200 300
2006-8-5 001 WS 100 200
2006-8-9 001 WS 50 150
......
现在我想查出8.1-8.5,所有会员各个品种的成交量(累加)和持有量(时间段内最后一天的数据),
结果应该是:
FirmID ClassID Qty HoldQty
001 WS 350 150
001 CF....
>现在我想查出8.1-8.5
结果应该是:
FirmID ClassID Qty HoldQty
001 WS 300 200
001 CF....
where date1<=Date<=date2
--->
where date1<=Date and Date<=date2
FirmID ClassID Qty HoldQty
001 WS 300 200====================================
语法小问题,修正:
where date1<=Date<=date2
--->
where date1<=Date and Date<=date2
----------------------------------
呵呵,谢谢你,我为了方便就简写成这样了,只要大家能理解就行,你就当是伪代码吧:)
真的写SQL时肯定不会这样写了,还要加一个to_date('date1','yyyymmdd')
from (
select a.*,sum(a.qty) over (partition by a.firmid,a.classid) sqty from firm a
where a.vdate between '2006-08-01' and '2006-08-05') x
where x.vdate = '2006-08-05'
这个日期 '2006-08-05'是不知道的,需要在库里查出来,比如我想查8.1-8.5的数据,有可能库里只有8.4的数据没有8.5的或有的记录有8.4和8.5(取8.5),有的只有8.4(取8.4)一天的记录。
没用过哦
我理解是由partition by后面的分组然后再order by一下,和group by的效果差不多
可以baidu一下它们两个的区别和用法。