简体   繁体   中英

calculate weekly and monthly sales from daily sales

If I have daily sales, how do I show weekly and monthly sales along with daily in a single record in oracle? I can calculate weekly sum and monthly sum in separate tables, but I want to the results in a single data set.

Output should look like shown below.

Date      Week  Month   Daily_Sale    Weekly_Sale Monthly_Sale
1/1/20      1      1        $5            $5          $5
1/2/20      1      1        $5            $10         $10
1/3/20      1      1        $1            $11         $11
1/4/20      1      1        $2            $13         $13
1/5/20      1      1        $5            $18         $18
1/6/20      1      1        $1            $19         $19
1/7/20      1      1        $1            $20         $20
1/8/20      2      1        $5            $5          $25
1/8/20      2      1        $5            $10         $30
1/10/20     2      1        $1            $11         $31
1/11/20     2      1        $2            $13         $33
1/12/20     2      1        $5            $18         $38
1/13/20     2      1        $1            $19         $39
1/14/20     2      1        $1            $20         $40

Thank you!

Edit: Highlighting the table

You seem to want running totals. Assuming that your tables contains sales information for more than a single year you need to partition on year as well.

select Date, extract(week from Date) Wk, extract(year from Date) Yr,
    Daily_Sale,
    sum(Daily_Sale) over (
        partition by extract(year from Date), extract(week from Date)
        order by Date
    ) as Weekly_Sale
    sum(Daily_Sale) over (
        partition by extract(year from Date), extract(month from Date)
        order by Date
    ) as Monthly_Sale
from T
order by Date;

I don't have oracle compiler so I replicated the scenario in SSMS. Here is the query:

SELECT T1.D1, T1.AnnualSales, T1.MonthlySales, T1.WeeklySales, T1.DailySales
 From
(SELECT [Date] As D1,
      Sum([Sales]) Over (Partition by Year(Date)) as AnnualSales,
      Sum([Sales]) Over (Partition by Month(Date)) as MonthlySales,
      Sum([Sales]) Over (Partition by Datepart(wk,Date)) as WeeklySales,
      Sum([Sales]) Over (Partition by Day(Date)) as DailySales
  FROM [dbo].[DailySales_Test]) AS T1
  Group by T1.D1, T1.AnnualSales, T1.MonthlySales, T1.WeeklySales, T1.DailySales

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM