[英]SQL - dynamic sum based on dynamic date range
我是SQL的新手,我甚至不確定我要實現的目標是否可行。
我有兩張桌子。 第一個給出一個帳號,一個“開始”日期和一個“結束”日期。 第二張表顯示每個帳戶的每月交易量。
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
我想以這樣的方式合並兩個表,使得表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
我相信,通過執行以下操作並將結果添加到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#
我想知道的是,是否有可能無需單獨填寫每個帳戶(有約1,000個帳戶)的Account#,Date_from和Date_to來實現此目的,但是可以自動完成日期表。
謝謝!
您應該可以使用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.