【问题标题】:Oracle SQL - trying to calculate running total with Group By without having an existing numerical column to sumOracle SQL - 尝试在没有现有数字列求和的情况下使用 Group By 计算运行总计
【发布时间】:2020-07-27 23:48:12
【问题描述】:

我想知道是否有人可以帮助我。我有以下表格结构,我试图获得按日期和产品分组的产品总数,即对于 Date_Ordered 中的每个不同日期,我希望列出每个不同的产品,以及总和它出现了多少次,包括那个日期。

+-----------+------------+--------------+-----+ |参考 |产品 | Date_Orderd | ... | +===========+=============+=============+=====+ | x-123123 |产品 1 | 2020 年 2 月 2 日 | ... | +-----------+------------+--------------+-----+ | x-123124 |产品 2 | 2020 年 2 月 2 日 | ... | +-----------+------------+--------------+-----+ | x-123125 |产品 3 | 2020 年 2 月 2 日 | ... | +-----------+------------+--------------+-----+ | ... | ... | ... | ... | +-----------+------------+--------------+-----+ | x-123241 |产品 2 | 2020 年 3 月 24 日 | ... | +-----------+------------+--------------+-----+ | x-123242 |产品 1 | 2020 年 3 月 25 日 | ... | +-----------+------------+--------------+-----+ | ... | ... | ... | ... | +-----------+------------+--------------+-----+ | x-123620 |产品 10 | 2020 年 2 月 5 日 | ... | +-----------+------------+--------------+-----+ | x-123621 |产品 7 | 2020 年 2 月 5 日 | ... | +-----------+------------+--------------+-----+

我遇到的问题是,我为此找到的所有示例(例如https://codingsight.com/calculating-running-total-with-over-clause-and-partition-by-clause-in-sql-server/https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1793764100346222947https://medium.com/better-programming/4-ways-to-calculate-a-running-total-with-sql-986d0019185c)似乎都假设表中有一个数值为总和。

有人知道是否有办法获取我需要的数据吗?

提前干杯。

【问题讨论】:

  • 最好根据你的例子展示一下最终数据的样子

标签: sql oracle count pivot window-functions


【解决方案1】:

如果给定的产品从未在同一数据上订购两次,您可以只使用窗口计数:

select
    t.*,
    count(*) over(partition by reference order by date_ordered) running_count
from mytable t

如果有重复,则需要聚合:

select  
    reference,
    date_ordered,
    sum(count(*)) over(partition by reference order by date_ordered) running_count
from mytable
group by reference, date_ordered

最后:如果你想生成日期和产品的所有组合,以及相关的运行计数,那么你会这样做:

select
    r.reference,
    d.date_ordered,
    sum(count(t.reference)) over(partition by r.reference order by d.date_ordered) running_count
from (select distinct date_ordered from mytable) d
cross join (select distinct reference from mytable) r
left join mytable t 
    on t.date_ordered = d.date_ordered and t.reference = r.reference
group by d.date_ordered, r.reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    相关资源
    最近更新 更多