2

我有一个佣金报告功能,可以获取员工的所有日常销售信息。 fCommissionINFO 我想做的是根据输出获取不同的信息并创建佣金报告。例如,该功能获取总客户数、特定销售的描述。我想做的是统计总销售额、特定销售额的总数和特定销售额的百分比。例如......如果“Sara”的总销售额为“100”......在这 100 个销售额中,她有 3 个服务“x”(总计 3%)、5 个服务 Y(5%)、6 个服务“z”(6%)等等等等……

我最初的 2 个存储函数调用是:

Select UserName, SUM(CarCount) AS Cars
FROM dbo.fCommissionINFO(@startdate, @endate, 'ALL', 'ALL', '1', 'ALL', 'Combined', '0') AS fCommissionINFO_1
WHERE (Services > 0)
GROUP BY UserName 

SELECT COUNT(Description) AS [service x]
FROM dbo.fCommissioninfo(@startdate, @endate, 'ALL', 'ALL', '1', 'ALL', 'Combined', '0') AS fCommissionINFO_1
WHERE (Description = 'service x')

我如何将这些结合起来,并结合第三个与用户名对齐?

4

3 回答 3

1

你需要这个查询

 SELECT UserName,            
        (SUM(COUNT(CASE WHEN Description = 'service x' THEN 1  END)) OVER() * 100) /
        SUM(CASE WHEN [Services] > 0 THEN CarCount END) AS percentage
 FROM dbo.fCommissioninfo(@startdate, @endate, 'ALL', 'ALL', '1', 'ALL', 'Combined', '0') AS fCommissionINFO_1
 GROUP BY UserName

SQLFiddle上的简单示例

于 2013-03-02T23:23:25.240 回答
0
Select UserName, SUM(CarCount) AS Cars, COUNT(Description) AS [service x]
FROM dbo.fCommissionINFO(@startdate, @endate, 'ALL', 'ALL', '1', 'ALL', 'Combined', '0') AS fCommissionINFO_1
WHERE (Services > 0)
GROUP BY UserName, Description
于 2013-02-22T12:22:02.633 回答
0

我相信以下应该可以解决问题。请注意将 where 子句提升到计数内部。这是因为如果有一行的服务 <= 0 并且描述为“服务 x”,它将被顶部查询排除并包含在底部查询中。因此,通过简单地组合查询,您可以获得不同的结果,具体取决于您的数据。

Select UserName, 
SUM(CASE WHEN Services > 0 THEN CarCount ELSE 0 END) AS Cars,
COUNT(CASE Description = 'service x' THEN 1 ELSE 0 END) 
FROM            dbo.fCommissionINFO(@startdate, @endate, 'ALL', 'ALL', '1', 'ALL', 'Combined', '0') AS fCommissionINFO_1
GROUP BY UserName 
于 2013-02-22T13:03:09.130 回答