0

我需要找出一周内有多少客户是新客户以及有多少是为员工返回的。

为了找出该员工上周有哪些客户,我查询:

 SELECT DISTINCT ClientIdNumber FROM Transactions
 WHERE [Date] >= @startDate AND [Date] <= @endDate
 AND EmployeeIdNumber = @employeeIdNumber

要了解客户和员工之前是否有过互动,我可以查询:

 IF (
     SELECT COUNT(*) AS n FROM Transactions
     WHERE [Date] < @startDate 
     AND ClientIdNumber = @clientIdNumber 
     AND EmployeeIdNumber = @employeeIdNumber
    ) > 0 
     SELECT 1 
  ELSE SELECT 0

我想将这些查询合并为一个,以便结果集如下所示:

EmployeeIdNumber - NewClients - ReturningClients

使用这两个单独的查询,我必须遍历第一个结果集并应用第二个结果集,这当然非常慢(而且很糟糕)

我无法理解它,因为我需要第二个查询中第一个查询的结果,但我确信有一个聪明的方法可以做到这一点。

4

2 回答 2

2

我并不完全清楚你所说的结果集应该看起来像“EmployeeIdNumber - NewClients - ReturningClients”是什么意思。如果您的意思是您希望每个人都EmployeeIdNumber返回新客户的数量和返回客户的数量,那么这是我的解决方案:

select
    t.EmployeeIdNumber,
    sum(case when t.count_before=0 then 1 else 0 end) as count_new_clients,
    sum(case when t.count_before>0 then 1 else 0 end) as count_returning_clients
from
    (
        select
            ClientIdNumber as ClientIdNumber,
            EmployeeIdNumber as EmployeeIdNumber,
            sum(case when [Date] >= @startDate and [Date] <= @endDate then 1 else 0 end) as count_last_week,
            sum(case when [Date] < @startDate then 1 else 0 end) as count_before
        from Transactions
        group by
            ClientIdNumber,
            EmployeeIdNumber
    ) t
group by
    t.EmployeeIdNumber
having
    t.count_last_week>0;
于 2013-07-30T03:53:26.173 回答
0

我认为最快的方法是:

with cte as (
    select distinct
        T.EmployeeIdNumber,
        T.ClientIdNumber,
        case
            when exists (
                select *
                from Transactions as TT
                where TT.[Date] < @startDate and TT.ClientIdNumber = T.ClientIdNumber
            ) then 1
            else 0
        end as Is_Old
    from Transactions as T
    where T.[Date] >= @startDate and T.[Date] <= @endDate
)
select
    EmployeeIdNumber,
    sum(case when Is_Old = 1 then 0 else 1 end) as NewClients,
    sum(case when Is_Old = 1 then 1 else 0 end) as ReturningClients
from cte
group by EmployeeIdNumber
于 2013-07-30T05:23:09.903 回答