0

我有两张桌子:

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

ResultedSales   (CustomerID,AppointmentID,ResultedDate)

我正在寻找约会中的记录,其中:

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

前三个是通过

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

任何帮助/提示?

4

3 回答 3

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 )
于 2013-03-20T20:44:35.833 回答
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)               
于 2013-03-20T22:43:19.497 回答
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)
于 2013-03-21T15:04:00.400 回答