簡體   English   中英

如何使用 oracle sql 匯總每月數據庫和以前的數據

[英]how to aggregate data base per month and previous data with oracle sql

假設我們有一個簡單的表格“示例”,如下所示:

id  time 
1  2-2-20 
2  3-1-20
3  15-2-20
4  20-3-20

我想按每個月計算包含上個月數據的行,並獲取每個月的平均數據(除以指定月份的行):

month rows_num avg_per_day
1-20    1        1/31
2-20    2+1      2/29
3-20    2+1+1    1/31

我正在考慮是否可以像這樣使用 sql 但不包含上個月的數據並且不知道如何處理平均值:

select count(*) from example group by trunc(to_date(trunc(time)),'MONTH')

任何人都可以幫助我嗎?

您可以使用:

select to_char(time, 'yyyy-mm') as month,
       sum(count(*)) over (order by min(time)) as rows_num,
       count(*) / extract(day from last_day(time))
from t
group by to_char(time, 'yyyy-mm'), extract(day from last_day(time))
order by min(time);

我對月份的格式略有不同,但您可以根據自己的喜好進行格式設置。

盡管查詢的 output 看起來相當簡單,但編寫內聯視圖以生成可在外部 SELECT 中使用的值可能是一個優勢,例如(使用您的示例表)

表格和數據

create table example ( id,  day_ )
as
select 1, date '2020-02-02' from dual union all --  2-2-20
select 2, date '2020-01-03' from dual union all --  3-1-20
select 3, date '2020-02-15' from dual union all -- 15-2-20
select 4, date '2020-03-20' from dual           -- 20-3-20
;

第一步(將其用於“內聯視圖”)

  select
    to_char( day_, 'MM-YY') month_
  , to_char( extract ( day from last_day( day_ ) ) ) lastday_
  , count(*) over ( order by to_char( day_, 'MM-YY') ) runningtotal_
  , row_number() over ( partition by  to_char( day_, 'MM-YY')  order by day_ ) rn_
  from example ;

-- result
+------+--------+-------------+---+
|MONTH_|LASTDAY_|RUNNINGTOTAL_|RN_|
+------+--------+-------------+---+
|01-20 |31      |1            |1  |
|02-20 |29      |3            |1  |
|02-20 |29      |3            |2  |
|03-20 |31      |4            |1  |
+------+--------+-------------+---+

最終查詢

select
  month_
, runningtotal_ rows_num
, round( max( rn_ )  / lastday_, 5 ) avg_per_day
, to_char( max( rn_ )  ) || '/' || to_char( lastday_ ) avg_per_day
from (
  select
    to_char( day_, 'MM-YY') month_
  , to_char( extract ( day from last_day( day_ ) ) ) lastday_
  , count(*) over ( order by to_char( day_, 'MM-YY') ) runningtotal_
  , row_number() over ( partition by  to_char( day_, 'MM-YY')  order by day_ ) rn_
  from example
)
group by month_, runningtotal_, lastday_
order by month_
;

-- result 
+------+--------+-----------+-----------+
|MONTH_|ROWS_NUM|AVG_PER_DAY|AVG_PER_DAY|
+------+--------+-----------+-----------+
|01-20 |1       |0.03226    |1/31       |
|02-20 |3       |0.06897    |2/29       |
|03-20 |4       |0.03226    |1/31       |
+------+--------+-----------+-----------+

DBfiddle 在這里

注意:(對我來說)您需要哪種形式的“AVG_PER_DAY”還不是很清楚。 只需從外部 SELECT 中刪除您不需要的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM