剛剛做項目的時候用到的
用戶表:用戶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
結果如下圖:
查出來了,網友建議最好流水表分表,如一月一表,要不然的話以后流水表會很大很大很大。。。
先這么弄着先吧。。