以下是我的表格:
[用户大师]
UserId Int, UserName Varchar(200),AddedBy Int
UserId EmpName AddedBy
1 admin 0
2 SubAdmin1 1
3 Vikas 2
4 Mohit 3
5 Atul 4
6 Vishal 2
7 Mani 3
8 Sunny 1
[销售大师]
SalesId Int, UserId Int (FK_UserMaster_UserId) , Price Int
SalesId UserId Price StatusId
10 1 100 1
11 2 200 1
12 3 300 1
13 4 500 1
14 5 100 2
15 6 200 1
16 7 111 2
17 8 222 1
[销售产品]
SaleProductId Int,SaleId Int (FK_SaleMaster_SaleId),数量 Int
SaleProductId SalesId Quantity
1 10 2
2 11 2
3 12 1
4 13 1
5 14 3
6 15 2
7 16 5
8 17 1
[输出]
结果集应该包含登录用户的销售额 + 他创建的用户以及他们的子用户创建的其他用户。
以下 TotalSalesAmount 是:
[SalesMaster].Price * [SalesProducts].Quantity
例如: UserId 的总销售额:1 为 100*2+200*2+ 300*1 + 500*1 +100*3 + 200*2 +111*5 + 222*1= 2877
同样对于 UserId:2 是 200*2+300*1 + 200*2 +500*1 + 111*5 +200*2= 2555
情况1:
如果 (admin)UserId=1 将登录,我们需要显示以下内容
UserId TotalSalesAmount OwnSaleAmount AddedBy
1 2877 200 0
2 2555 400 1
3 1355 300 2
4 800 500 3
5 100*3= 300 300 4
6 200*2=200 200 2
7 111*5= 555 555 3
8 222*1= 222 222 1
案例 2:如果 (Vikas)UserId=3 将登录,我们需要显示以下内容
UserId TotalSalesAmount OwnSaleAmount AddedBy
3 300*1 + 500*1 + 111*5= 1355 300 2
4 500*1 + 100*3= 800 500 3
5 100*3= 300 300 4
7 111*5= 555 555 3
表格脚本和数据在这里,我使用过 http://test-admin.teamberry.biz/SalesScript.rar ,
运行此脚本后,请执行以下查询 take UM.UserId=164, SM.statusID = 1 UserId=166 的 TotalSalesAmount 出错了,因为它的 TotalSaleAmount 应该与 ownSaleAmount 相同,即 444,因为 UserId=166 没有任何孩子。
with tblOwnSaleAmount as
(
select UM.UserId,UM.EmpName,UM.AddedBy,cast(sum( SM.Price*SP.Quantity) as int) as OwnSaleAmount
from UserMaster UM
left join SalesMaster SM on SM.UserId = UM.UserId and SM.statusID = 1
left join SalesProducts SP on SP.SalesId = SM.SalesId
where UM.UserId = 164
group by UM.UserId ,UM.AddedBy,UM.EmpName
union all
select UM.UserId,UM.EmpName, UM.AddedBy,
case when SM.statusID = 1 then cast(( SM.Price*SP.Quantity ) as int)
else 0 end as OwnSaleAmount
from UserMaster UM
join tblOwnSaleAmount on tblOwnSaleAmount.UserId = UM.AddedBy
join SalesMaster SM on SM.UserId = UM.UserId
join SalesProducts SP on SP.SalesId = SM.SalesId
)
, tbldistinctOwnSaleAmount as
(
select distinct UserId,EmpName, AddedBy,Isnull(OwnSaleAmount,0) as OwnSaleAmount
from tblOwnSaleAmount
)
,
tblTotalOwnSaleAmount as
(
select OSA.UserId,OSA.EmpName, OSA.AddedBy, sum( OSA.OwnSaleAmount ) as OwnSaleAmount
from tbldistinctOwnSaleAmount OSA --inner join tbldistinctOwnSaleAmount A on OSA.AddedBy = A.UserID
group by OSA.UserId ,OSA.AddedBy,OSA.EmpName
)
select OSA.*
, TotalSalesAmount = isnull(
(
select sum( OSA1.OwnSaleAmount )
from tblTotalOwnSaleAmount OSA1
where OSA1.UserId > OSA.UserId
), 0 )
+ OSA.OwnSaleAmount
from tblTotalOwnSaleAmount OSA
order by OSA.UserId