[英]SQL - dynamic sum based on dynamic date range
I'm new to SQL and I'm not even sure if what I am trying to achieve is possible. 我是SQL的新手,我甚至不确定我要实现的目标是否可行。
I have two tables. 我有两张桌子。 The first gives an account number, a 'from' date and a 'to' date. 第一个给出一个帐号,一个“开始”日期和一个“结束”日期。 The second table shows monthly volume for each account. 第二张表显示每个帐户的每月交易量。
Table 1 - Dates
Account# Date_from Date_to
-------- --------- -------
123 2018-01-01 2018-12-10
456 2018-06-01 2018-12-10
789 2018-04-23 2018-11-01
Table 2 - Monthly_Volume
Account# Date Volume
--------- ---------- ------
123 2017-12-01 5
123 2018-01-15 5
123 2018-02-05 5
456 2018-01-01 10
456 2018-10-01 15
789 2017-06-01 5
789 2018-01-15 10
789 2018-06-20 7
I would like to merge the two tables in such a way that each account in Table 1 has a fourth column that gives the sum of Volume between Date_from and Date_to. 我想以这样的方式合并两个表,使得表1中的每个帐户都具有第四列,该列给出了Date_from和Date_to之间的交易量总和。
Desired Result:
Account# Date_from Date_to Sum(Volume)
-------- --------- ------- -----------
123 2018-01-01 2018-12-10 10
456 2018-06-01 2018-12-10 15
789 2018-04-23 2018-11-01 7
I believe that this would be possible to achieve for each account individually by doing something like the following and joining the result to the Dates table: 我相信,通过执行以下操作并将结果添加到Dates表中,可以单独为每个帐户实现此目标:
SELECT
Account#,
SUM(Volume)
FROM Monthly_Volume
WHERE
Account# = '123'
AND Date_from >= TO_DATE('2018-01-01', 'YYYY-MM-DD')
AND Date_to <= TO_DATE('2018-12-10', 'YYYY-MM-DD')
GROUP BY Account#
What I'd like to know is whether it is possible to achieve this without having to individually fill in the Account#, Date_from and Date_to for each account (there are ~1,000 accounts), but have it be done automatically for each entry in the Dates table. 我想知道的是,是否有可能无需单独填写每个帐户(有约1,000个帐户)的Account#,Date_from和Date_to来实现此目的,但是可以自动完成日期表。
Thank you! 谢谢!
You should be able to use join
and group by
: 您应该可以使用join
和group by
:
select d.account#, d.Date_from, d.Date_to, sum(mv.volume)
from dates d left join
monthly_volume mv
on mv.account# = d.account# and
mv.date between d.Date_from and d.Date_to
group by d.account#, d.Date_from, d.Date_to;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.