Sql Server - 仅为活动用户获取值的 SUM()
Posted
技术标签:
【中文标题】Sql Server - 仅为活动用户获取值的 SUM()【英文标题】:Sql Server - Get SUM() of values for only Active Users 【发布时间】:2021-03-03 02:46:48 【问题描述】:我有一个要求,我需要按 RegionId 获取总活跃员工和总销售额
我的查询结果应该如下所示。
RegionId | TotalEmployees | TotalSales | Average
1 10 100 10
2 3 15 5
我的前端应用程序会将所有 RegionIds 作为用逗号分隔的单个字符串传递,我的查询参数是 VARCHAR() 类型,输入参数看起来像 '1,2,3,4,7,14, 26',单个字符串中最多可以有 20 个 Region Id,以逗号分隔。
SELECT E.[RegionId] as RegionId
,COUNT(E.[EmployeeId) AS TotalEmployees
,(SELECT SUM([Sale])
FROM dbo.[Sales]
WHERE RegionId = R.[RegionId]
) AS TotalSales
,TotalSales/TotalEmployees AS Average
FROM dbo.[Employee]
JOIN [dbo].[ufn_StringSplit](@RegionIdCollection, ',') RegionId
ON E.RegionId = CAST(RegionId.[Data] AS Varchar(5000))
WHERE E.[Active] = 1
GROUP BY E.[RegionId]
我的 Employee 表结构如下所示
EmployeeId | Name | RegionId | Active
100 Tom 2 1
101 Jim 4 0
103 Ben 2 1
销售表
SaleId | EmployeeId| RegionId | Sale
1 100 2 3500
2 101 4 2000
3 100 2 1500
现在我的问题是当我获取 TotalSales 时,以下查询按 RegionId 获取所有销售,但我需要获取仅由 Employee 表中当前活跃员工完成的所有销售
(SELECT SUM([Sale])
FROM dbo.[Sales]
WHERE RegionId = R.[RegionId]
) AS TotalSales
【问题讨论】:
我假设您的Sales
表中有一个EmployeeId
列?
【参考方案1】:
没有理由使用子选择在此处查找sales
的sum
,这将导致为每一行运行该查询。你想以一种基于集合的方式来解决这个问题,这意味着你需要适当地 join
和 group
:
with s as
(
select e.RegionId
,e.EmployeeId
,sum(s.Sale) as EmployeeSales
from dbo.ufn_StringSplit(@RegionIdCollection, ',') as r
join dbo.Employee as e
on r.RegionId = CAST(r.[Data] AS varchar(20)) -- Do you really need 5000 characters here?
left join dbo.Sales as s
on r.RegionId = s.RegionId
and e.EmployeeId = s.EmployeeId
where e.Active = 1
group by e.RegionId
,e.EmployeeId
)
select s.RegionId
,count(s.EmployeeId) as TotalEmployees
,sum(s.EmployeeSales) as TotalSales
,sum(s.EmployeeSales)/count(s.EmployeeId) as Average
from s
group by s.RegionId
【讨论】:
你好 Dave,尝试了你的查询,TotalSales 值现在很完美,但 TotalEmployees 计数已经搞砸了,我在我的问题中发布了查询,总活跃 TotalEmployees 值很完美 @claudia “计数搞砸了” - 请具体说明;如果你不告诉我出了什么问题,我无法帮助你。查看我假设现在太高的查询?以上是关于Sql Server - 仅为活动用户获取值的 SUM()的主要内容,如果未能解决你的问题,请参考以下文章
如何在sql server和s-s-rs中获取多个值以及空值