0

私は2つのテーブルを持っています:

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

ResultedSales   (CustomerID,AppointmentID,ResultedDate)

アポイントメントでレコードを探しています。

  1. ステータスが表示されます(保留中、キャンセル済み、オープンなどではなく)
  2. 顧客は以前に販売されました(ResultedSalesのCustomerID)
  3. Appointmentは販売として生成されませんでした(AppointmentIDはResultedSalesに含まれていません)
  4. Appointmentは、顧客が最初に販売された後に発生します
    (AppointmentDate>そのCustomerIDのResultedSalesの最小のAppointmentIDレコードのAppointmentDate)
  5. アポイントメントに割り当てられたSalesRepは、前の販売と同じです
    (SalesRepID =そのCustomerIDのResultedSalesのAppointmentIDレコードのSalesRepID)

最初の3つはで達成されます

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

http://msdn.microsoft.com/en-us/library/ms188336.aspxでMSDN情報を確認してください。EXISTS

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 に答える