【问题标题】:SQL - dynamic sum based on dynamic date rangeSQL - 基于动态日期范围的动态总和
【发布时间】:2019-05-11 17:50:31
【问题描述】:

我是 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#

我想知道的是是否有可能实现这一点,而不必为每个帐户单独填写 Account#、Date_from 和 Date_to(大约有 1,000 个帐户),但是否可以为每个帐户自动完成Dates 表中的条目。

谢谢!

【问题讨论】:

    标签: sql oracle dynamic aggregation


    【解决方案1】:

    您应该可以使用joingroup 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 2013-06-28
      • 1970-01-01
      • 2016-04-19
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多