我有两张桌子:
Appointments (CustomerID,AppointmentID,SalesRepID,Status,AppointmentDate)
ResultedSales (CustomerID,AppointmentID,ResultedDate)
我在Appointments中寻找记录:
前三个是用
实现的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
任何帮助/提示?
答案 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
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)