繁体   English   中英

SQL笛卡尔积(与group by求和)

[英]Sql cartesian product (summing with group by)

我正在尝试计算important_stock_dates日表中特定日期的一组股票最近30天的交易量总和。 all_stock_dates包含相同的股票,但是具有所有日期的交易量,而不仅仅是特定日期。

样本数据

all_stock_dates

stockid, date, volume  
0231245, 20060314, 153  
0231245, 20060315, 154  
2135411, 20060314, 23  

Important_stock_dates

stockid, date, thirtydaysprior  
0231245, 20060314, 20060130  
0231245, 20060315, 20060201  
2135411, 20060314, 20060130  

我的密码

create table sum_trading_volume as
select a.stockid, a.date, sum(b.volume) as thirty_day_volume
from important_stock_dates a, all_stock_dates b
where b.date<a.date AND b.date ge a.thirtydaysprior
group by a.stockid, a.date;

期望的结果

与所有观察的表important_stock_dates还具有体积的基于匹配stockid和日期前30天的总和all_stock_dates

问题

我遇到的问题是, important_stock_dates有15万条款的意见和all_stock_dates拥有350万美元。 运行此代码会占用数百GB的交换文件(使硬盘驱动器最大),然后中止。 我看不到如何优化代码。 我在StackOverflow或Google上找不到类似的问题。

大概,您想要的查询在stockidstockid

create table sum_trading_volume as
    select isd.stockid, isd.date, sum(asd.volume) as thirty_day_volume
    from important_stock_dates isd join
         all_stock_dates asd
         on isd.stockid = asd.stockid and
            asd.date < isd.date and asd.date >= isd.thirtydaysprior
    group by isd.stockid, isd.date;

如果这样做有效,则可能会完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM