一條SQL語句中算日銷售額和月銷售額


 

剛剛做項目的時候用到的

用戶表:用戶ID,用戶名,余額

流水表:時間,用戶ID,用戶名,類型(0充值,1消費),變更金額

現在要查每個用戶的日銷售額和月銷售額,本來最簡單的方法是先把所有用戶查出來,然后再c#代碼中for循環中再select sum(changemoney) from liushui where userid=? 的

現在想試試看一個SQL語句 就查出來,經搜索得到如下 SQL語句:

 

WITH DailySales AS(
	select [user].id,[user].username,[user].balance,
	case
		when sum([liushui].changemoney) is NULL then 0
		else sum([liushui].changemoney)
	end as ri_xse 
	from [user]
	left join [liushui] on [user].id=[liushui].userid and [liushui].type=1 and [liushui].createtime between '2017-07-11 00:00:00' and '2017-07-11 23:59:59' 
	group by [user].id,[user].username,[user].balance
)
,MonthSales AS(
	select [user].id,[user].username,[user].balance,
	case
		when sum([liushui].changemoney) is NULL then 0
		else sum([liushui].changemoney)
	end as yue_xse 
	from [user]
	left join [liushui] on [user].id=[liushui].userid and [liushui].type=1 and [liushui].createtime between '2017-07-01 00:00:00' and '2017-07-31 23:59:59' 
	group by [user].id,[user].username,[user].balance
) select d.id,d.username,d.balance,d.ri_xse,m.yue_xse from DailySales D inner join MonthSales M on D.id = M.id

結果如下圖:

查出來了,網友建議最好流水表分表,如一月一表,要不然的話以后流水表會很大很大很大。。。

先這么弄着先吧。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM