【问题标题】:Weekly/monthly/quarterly grouping in query查询中的每周/每月/每季度分组
【发布时间】:2012-03-19 11:13:32
【问题描述】:

假设我有以下列的表格

1. Client - string.
2. Profit - integer.
3. Deal_Date - date.

我需要按周/月/季度等检索利润细分总和的查询。

几周的预期产出

1 row, sum (profit) of all deals that registered from (03.19.2012 - 03.12.2012).
2 row, sum (profit) of all deals that registered from (03.12.2012 - 03.05.2012).
...
n row, sum (profit) of all deals that registered from (05.17.2011 - 05.10.2011).

注意(日期仅作为示例)

月、年等都一样

有人可以帮我解决这样的问题吗?

顺便说一句,性能非常重要。

【问题讨论】:

  • 你能显示你想要的输出吗?您需要代表什么日期范围?当您说“性能非常重要”时,您的标准是什么?你在说多少数据?

标签: sql oracle time grouping


【解决方案1】:

此查询使用简单的日期格式来提取您想要跟踪和分析的各种元素以获得总和。

select client
       , yr
       , qtr
       , wk
       , sum ( profit ) over ( partition by client, yr) as yr_profit
       , sum ( profit ) over ( partition by client, yr, qtr) as qtr_profit
       , sum ( profit ) over ( partition by client, yr, wk) as wk_profit
from ( 
         select client
                , profit
                , to_char(deal_date, 'yyyy') as yr
                , to_char(deal_date, 'q') as qt
                , to_char(deal_date, 'ww') as wk
          from your_table )
/

这将为当前表中的每一行生成一行。因此,您可能希望将其包装在仅返回不同行的进一步外部查询中。

一种变体是使用汇总。我不确定当分组标准不是完全分层(周不能整齐地划分为季度)时,它的效果如何。

select client
       , yr
       , qtr
       , wk
       , sum ( profit ) as profit
from ( 
         select client
                , profit
                , to_char(deal_date, 'yyyy') as yr
                , to_char(deal_date, 'q') as qt
                , to_char(deal_date, 'ww') as wk
          from your_table )
group by rollup ( client, yr, qtr, wk )
/

【讨论】:

    【解决方案2】:

    只需创建一个 SP 并根据需要循环每周、每月或每年的代码。

    【讨论】:

    • 这在 1997 年可能是一个糟糕的答案,但现在 Row By Agonizing Row 是不可接受的。在过去的 15 年里,甲骨文确实取得了进步,并提供了许多不同的、性能更好的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多