假设我有一些包含以下列的表
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).
注意(例如日期设置)
月,年等相同
有人可以帮我解决这个问题吗?
Btw的表现非常重要。
答案 0 :(得分:4)
此查询使用简单的日期格式来提取您要跟踪的各种元素和分析以获取总和。
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 )
/
答案 1 :(得分:-2)
只需制作一个SP并根据需要循环每周或每月或每年的代码。