簡體   English   中英

T-SQL 查詢匯總所有年份的銷售額:每年每月總計,以及每月累計金額

[英]T-SQL query to summarize sales for ALL YEARS: with total per month per year, and cumulative monthly amounts

我需要創建一個銷售報告,顯示每月所有年份的銷售額和累計銷售額。 數據庫表很簡單:

Transactions 
(
    ID INT, 
    TransactionDate DATETIME, 
    SalesAmount MONEY
)

我希望結果看起來類似於下面的 ExcelSheet(我只顯示 2017/2018 年的金額,但實際查詢需要根據 TransactionDate 返回所有可用年份的結果)

在此處輸入圖片說明

這是聚合和累積總和:

select year(TransactionDate), month(TransactionDate),
       sum(SalesAmount),
       sum(sum(SalesAmount)) over (partition by year(TransactionDate) order by min(TransactionDate))
from Transactions
group by year(TransactionDate), month(TransactionDate)
order by year(TransactionDate), month(TransactionDate);

嘗試一下:

With Q 
as
(
   Select DatePart(yyyy,TransactionDate) 'Year',DatePart(m,TransactionDate) 'Month',  sum(SalesAmount) 'Sales'
   From Transactions 
   Group by DatePart(yyyy,TransactionDate),DatePart(m,TransactionDate)
) 
Select q.Year,q.Month,q.sales,( Select sum(q1.Sales)
        From Q q1
        Where q1.Year=q.Year
         And  q1.Month <= q.Month
        ) 'Cumulative Sale'
From Q q
Order by q.Year,q.Month

嘗試這個:

with cte as
(
select year(TransactionDate) as Year, month(TransactionDate) as Month, SalesAmount 

)

 select a.Year, a.Month, a.SalesAmount, sum(b.SalesAmount) as cumulativeSalesAmount 
 from Transactions  a inner join Transactions  b on a.STORE_ID = b.STORE_ID and a.Year = b.Year and a.Month >= b.Month
 group by a.Year, a.Month
 order by 1, 2

暫無
暫無

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

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