Reputation: 3207
I have two tables (let's call them TradingWindows and VolumeData). Each row of TradingWindows has a startBin and endBin for each different stock. In VolumeData, there are columns stock,binIndex,volume.
I want to combine this information by doing the following operation: for-each row in the TradingWindows table I want to sum up the all the volume binIndex's that are > startBin and < endBin. (the idea is to get the total volume between start and end).
Now, coming from a procedural programming background this is easy (just write a for-each loop). I know this is possible in SQL, but I am new and was wondering if there is a more efficient way to do it.
Thanks!
Upvotes: 2
Views: 5791
Reputation: 5747
I'm making some guesses on your table structure, but I think you're looking for something like this:
Select VD.stock, Sum(volume)
From VolumeData VD
Inner Join TradingWindows TW On VD.stock = TW.stock
Where VD.binIndex Between TW.startBin And TW.endBin
Group By VD.stock
This will match up your VolumeData rows to your TradingWindow rows (by stock), filter out the VolumeData rows which aren't in your range, and group them together by stock.
EDIT: Here's a non-inclusive version (as JNK points out, BETWEEN will include startBin and endBin):
Select VD.stock, Sum(volume)
From VolumeData VD
Inner Join TradingWindows TW On VD.stock = TW.stock
Where VD.binIndex > TW.startBin And VD.binIndex < TW.endBin
Group By VD.stock
Upvotes: 5