2013-07-30 78 views
0

我需要找出有多少客户是新的,以及一周内员工返回的人数。结合两条sql语句需要帮助

要找出客户的员工上周有,我查询:

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

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

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

回答

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 
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;