需要帮助组合两个sql语句

时间:2013-07-30 02:53:27

标签: tsql sql-server-2008-r2

我需要知道有多少客户是新的,有多少客户在一周内回来。

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

 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

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

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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