简体   繁体   English

SQL For-each循环替代

[英]SQL For-each Loop Alternative

I have two tables (let's call them TradingWindows and VolumeData). 我有两个表(我们称它们为TradingWindows和VolumeData)。 Each row of TradingWindows has a startBin and endBin for each different stock. TradingWindows的每一行都有每种不同股票的startBin和endBin。 In VolumeData, there are columns stock,binIndex,volume. 在VolumeData中,有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. 我想通过执行以下操作来组合此信息:TradingWindows表中的for-each行,我想总结> startBin和<endBin的所有量binIndex。 (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). 现在,从过程编程的背景出发,这很容易(只需编写一个for-each循环)。 I know this is possible in SQL, but I am new and was wondering if there is a more efficient way to do it. 我知道这在SQL中是可行的,但是我是新手,我想知道是否有更有效的方法来做到这一点。

Thanks! 谢谢!

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. 这会将您的VolumeData行与TradingWindow行(按库存)匹配,过滤掉不在您范围内的VolumeData行,然后按库存将它们分组在一起。

EDIT: Here's a non-inclusive version (as JNK points out, BETWEEN will include startBin and endBin): 编辑:这是一个非包含版本(如JNK所指出的,BETWEEN将包括startBin和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

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

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