SQL——處理行的累加,sql處理累加

來源:互聯網
上載者:User

SQL——處理行的累加,sql處理累加


       背景:


              現在有一張報表,其中上面的資料是商家的訂單資料,按照天統計的,要從訂單表查出每天的某個商家的訂單量,然後去日收益表查出這天的這個商家的收益額,然後還要統計出在某天之前的所有收益額,然後從查出的這種表裡篩選出某個時間段的記錄。


            下面是SQL:


ALTER PROCEDURE [dbo].[sp_LoadSellerDataByTime]@SellerCode NVARCHAR(36), --商家編碼@StartTime CHAR(20), --起始日期@EndTime CHAR(20),--終止日期@pageSize INT=31, --一頁內有多少條資料 @pageIndex INT=1 --第幾頁  ASDECLARE @totalCount INT --返回資料條數--每日營業額表SELECT * INTO #temp_Count FROM(SELECT  LEFT(convert(varchar,table0.CreateTime,21),10) AS MonthDate/*本條日期*/,SUM(table0.TotalCharge) AS SumMonthMoney/*今天總營業額*/FROM [CommunityCatering].[Catering].[SellerIncome] table0WHERE table0.SellerCode=@SellerCode/*sellerCode*/GROUP BY LEFT(convert(varchar,table0.CreateTime,21),10) ) AS tempCount--查總金額SELECT * INTO #MainTable FROM(SELECT MonthDate,SumMonthMoney,SumTotalMoney,ISNULL(TotalCount,0) AS TotalCount FROM (SELECT MonthDate,SumMonthMoney,SumTotalMoney=(SELECT SUM(SumMonthMoney)    FROM #temp_Count t1WHERE t1.MonthDate<=t2.MonthDate) FROM #temp_Count t2)AS SILEFT JOIN(/*查每日訂單數量*/ SELECT  LEFT(convert(varchar,Ord.CompleteTime,21),10) AS MonthDate1, COUNT(1) AS TotalCount/*訂單數量*/ FROM CommunityCatering.Catering.[Order] Ord  WHERE ord.CompleteTime IS NOT NULL AND ord.ValidStatus=5/*有效性:選擇已經完成的訂單*/AND ord.SellerCode=@SellerCode/*商家code*/ GROUP BY LEFT(convert(varchar,Ord.CompleteTime,21),10)) AS temp ON SI.MonthDate=temp.MonthDate1) AS MainTable SELECT *,ROW_NUMBER() OVER(ORDER BY #MainTable.MonthDate) AS RowNum/*分頁需要欄位*/  FROM  #MainTable WHERE  #MainTable.MonthDate BETWEEN @StartTime AND @EndTime /*去開始時間結束時間的資料*/  --計算總的資料條數 SELECT @totalCount=ISNULL(COUNT(1),0)  FROM #MainTable WHERE #MainTable.MonthDate BETWEEN @StartTime AND @EndTime --輸出總的資料條數 SELECT @totalCount AS TotalCount--刪除暫存資料表 DROP TABLE #MainTable DROP TABLE #temp_Count


     如上代碼:

               例如:第一列代表天,第二列代表當天營業額,第三列代表本天之前的所有營業額,可以看出第三列是第二列的一個累加。




            在SQL中,這裡首先定義一個暫存資料表,然後使用一個小的巢狀查詢,在這個巢狀查詢裡面,我們計算出前面每天營業額的累加。







         

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.