查询以在一个表中选择记录存在于另一个表中的记录

时间:2013-03-20 20:29:24

标签: sql-server

我有两张桌子:

Appointments    (CustomerID,AppointmentID,SalesRepID,Status,AppointmentDate)

ResultedSales   (CustomerID,AppointmentID,ResultedDate)

我在Appointments中寻找记录:

  1. 结果是状态(与待处理,取消,打开等相反)
  2. 客户已售出(之前在ResultedSales中的客户ID)
  3. 预约不是作为销售产生的(AppointmentID不在ResultedSales中)
  4. 预约发生在客户第一次出售后 (AppointmentDate>该CustomerID的ResultedSales中最小的AppointmentID记录的约会日期)
  5. 分配到约会的SalesRep与之前的促销相同 (SalesRepID =该CustomerID的ResultedSales中任何AppointmentID记录的SalesRepID)
  6. 前三个是用

    实现的
    Select Distinct .AppointmentID from Appointments A
        join ResultedSales RS on A.CustomerID=RS.CustomerID
    Where A.StatusID='resulted'
    And A.CustomerID in (Select CustomerIDfrom ResultedSales)
    And A.AppointmentID Not in (select AppointmentID from ResultedSales)
    

    但我无法弄清楚如何实现#4和#5

    任何帮助/提示?

3 个答案:

答案 0 :(得分:0)

Select Distinct .AppointmentID from Appointments A
    join ReportedSales RS on A.CustomerID=RS.CustomerID
Where A.StatusID='resulted'

and exists ( select null from ResultedSales innerRSTable1 where innerRSTable1.CustomerID = A.CustomerID)
and not exists ( select null from ResultedSales innerRSTable2 where innerRSTable2.AppointmentID = A.AppointmentID )

答案 1 :(得分:0)

查看EXISTS http://msdn.microsoft.com/en-us/library/ms188336.aspx

上的MSDN信息
Select  Distinct A.AppointmentID 
from    Appointments A
join    ResultedSales RS 
        on  A.CustomerID=RS.CustomerID
Where   A.StatusID='resulted'
And     Not Exists (Select 1 
                    From    ResultedSales rs2
                    Where   A.AppointmentID = rs2.AppointmentID)
And     Exists (Select  1
                From    Appointments A2
                Where   A.CustomerID=A2.CustomerID
                And     A.AppointmentDate > A2.AppointmentDate)
And     Exists (Select  1
                From    Appointments A3
                Where   A.CustomerID=A3.CustomerID
                And     A.SalesRepID = A2.SalesRepID)               

答案 2 :(得分:0)

从另一个论坛得到了另一个回复,它似乎正在执行查询所要求的内容。

;WITH FirstSales (CustomerID, AppointmentDate, SalesRepID)
AS (
SELECT DISTINCT 
   A.CustomerID
   , MIN(AppointmentDate)
   , A.SalesRepID
FROM ResultedSales RS
JOIN Appointments A
   ON A.AppointmentID = RS.AppointmentID 
   AND A.CustomerID = RS.CustomerID
WHERE StatusID = 'Resulted'
GROUP BY A.CustomerID, A.SalesRepID
)

SELECT DISTINCT 
    A.AppointmentID
FROM Appointments A
    JOIN ResultedSales RS
        ON RS.CustomerID = A.CustomerID
    JOIN FirstSales FS
        ON FS.CustomerID = A.CustomerID
WHERE A.StatusID = 'Resulted'
AND A.AppointmentDate > FS.AppointmentDate
AND A.SalesRepID = FS.SalesRepID
AND A.AppointmentID Not in (select AppointmentID from ResultedSales)