SQL查询按时间段到日期聚合
Posted
技术标签:
【中文标题】SQL查询按时间段到日期聚合【英文标题】:SQL query to aggregate by period through date 【发布时间】:2019-12-09 19:48:54 【问题描述】:我有一个表,其中包含按商店编号和交易日期划分的交易数据。它还包括相应交易日期的年份和期间编号,例如:
create table transactional_data (
store_id number,
tran_date date,
year number,
period_no number,
orders number,
sales number
);
我需要一个查询,该查询将为每个 tran_date 返回一行,其中包括该期间当天的订单和销售额的总和。
例如,如果我在表格中有以下内容:
STORE_ID TRAN_DATE YEAR PERIOD_NO ORDERS SALES
10 2019-01-01 2019 1 10 119.12
10 2019-01-02 2019 1 15 201.56
10 2019-01-03 2019 1 13 167.92
我希望查询的结果是:
STORE_ID TRAN_DATE YEAR PERIOD_NO ORDERS_PTD SALES_PTD
10 2019-01-01 2019 1 10 119.12
10 2019-01-02 2019 1 25 320.68
10 2019-01-03 2019 1 38 488.60
我可以轻松地按期间完成分组,以提供商店在整个期间的总订单和销售额,但我无法找到一种方法来分解每个交易日期的期间到日期销售额。
如何做到这一点?
【问题讨论】:
【参考方案1】:您只想要每个商店在每个时期的累计金额吗?
select t.*,
sum(sales) over (partition by store_id, period_no order by trans_date)
from transactional_data t;
如果你想组合给定日期的值,你可以使用聚合:
select store_id, trunc(trans_date), year, period_no,
sum(orders), sum(sales),
sum(sum(sales)) over (partition by store_id, period_no order by trunc(trans_date)
from transactional_data t
group by store_id, trunc(trans_date), year, period_no;
【讨论】:
【参考方案2】:试试这个:
select 10 as STORE_ID, '2019-01-01' as TRAN_DATE, 2019 as YEAR, 1 as PERIOD_NO, 10 as ORDERS, 119.12 as SALES into #tmp
union select 10, '2019-01-02', 2019, 1, 15, 201.56
union select 10, '2019-01-03', 2019, 1, 13, 167.92
select a.STORE_ID, a.TRAN_DATE, a.YEAR, a.PERIOD_NO, sum(b.ORDERS) as ORDERS_PTD , sum(b.sales) as SALES_PTD
from #tmp a inner join #tmp b on a.STORE_ID = b.STORE_ID and a.PERIOD_NO = b.PERIOD_NO and a.TRAN_DATE >= b.TRAN_DATE
group by a.STORE_ID, a.TRAN_DATE, a.YEAR, a.PERIOD_NO, a.[ORDERS]
order by 2
【讨论】:
【参考方案3】:你可以使用sum() over (partition by .. order by ...)
解析函数两次:
select t.*,
sum(orders) over (partition by store_id order by tran_date) as orders_ptd,
sum(sales) over (partition by store_id order by tran_date) as sales_ptd
from transactional_data t
order by tran_date;
Demo
【讨论】:
以上是关于SQL查询按时间段到日期聚合的主要内容,如果未能解决你的问题,请参考以下文章