2011-03-25 119 views
1

我很難以看到這個查詢。我有一個交易表爲不同的醫生交易。交易和醫生之間有多對多的交易(每筆交易可能有超過一名醫生)。我需要找到最接近醫生的交易,以給定用戶的經度和緯度。我有一個存儲過程,負責查找距離。SQL:基於另一個列聚合一列

Select d.dealID, do.doctorID, 
    dbo.fn_latlongdist($userlat,$userlong,do.doctorLatitude,do.doctorLongitude) as distance 
    From y_Deals d 
    JOIN y_deals_doctor dd ON dd.dealID = d.dealID 
    JOIN Doctor do on dd.doctorID = do.doctorID 
    ORDER BY distance 

現在我想按dealID分組,所以我不會返回多個交易。問題是我想以最小距離返回doctorID。似乎沒有任何聚合函數會圍繞doctorID,它會返回帶有最小距離列的doctorID。

我該如何解決這個問題?

+1

難道你不能只選擇頂行嗎?選擇Top 1 ... – 2011-03-25 17:09:12

+0

醫生表是否包含有關其位置的一些信息? – Leslie 2011-03-25 17:09:14

+0

@amit_g我不想要只有頂部1,我想要一個距離交易列表,但我想知道最接近的每個醫生 – DannyLeavitt 2011-03-25 17:11:41

回答

1

看看這對你的作品

Select * From 
(
    Select 
      d.dealID 
     , do.doctorID 
     , dbo.fn_latlongdist($userlat, $userlong, do.doctorLatitude, do.doctorLongitude) as Distance 
     , ROW_NUMBER() OVER (PARTITION BY d.dealID ORDER BY dbo.fn_latlongdist($userlat, $userlong, do.doctorLatitude, do.doctorLongitude)) AS RowNumber 
    From 
     y_Deals d 
    JOIN 
     y_deals_doctor dd ON dd.dealID = d.dealID 
    JOIN 
     Doctor do on dd.doctorID = do.doctorID 
) T 
Where 
    T.RowNumber = 1 

UPDATE:

;With AllData As 
(
    Select 
      d.dealID 
     , do.doctorID 
     , dbo.fn_latlongdist($userlat, $userlong, do.doctorLatitude, do.doctorLongitude) as Distance 
     , ROW_NUMBER() OVER (PARTITION BY d.dealID ORDER BY dbo.fn_latlongdist($userlat, $userlong, do.doctorLatitude, do.doctorLongitude)) AS RowNumber 
    From 
     y_Deals d 
    JOIN 
     y_deals_doctor dd ON dd.dealID = d.dealID 
    JOIN 
     Doctor do on dd.doctorID = do.doctorID 
) 
,DrCount As 
(
    Select 
      dealID 
     , Count(Distinct doctorID) as doctorCount 
    From 
     AllData 
    Group By 
     dealID 
) 
Select 
    * 
From 
    AllData A 
Inner Join 
    DrCount C 
On 
    A.dealID = C.dealID 
Where 
    A.RowNumber = 1 
+0

這個工程。有沒有什麼辦法可以返回一列,顯示最初有多少醫生被納入交易? – DannyLeavitt 2011-03-25 19:44:12

+0

更新了代碼。再次確保正確測試。 – 2011-03-25 19:55:57

+0

哇,這個作品。非常感謝!運行速度也很快。 – DannyLeavitt 2011-03-25 21:16:24

0

另一種選擇是使用http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/討論的技術。它不依賴於ROW_NUMBER(),它不適用於很多數據庫引擎。

下面是一個示例,其中distance是醫生表中的列而不是計算的函數。根據需要調整:

SELECT 
    Doctors.ID, DoctorName, Distance, DealName 
FROM 
    (SELECT DealID, Min(Doc.Distance) as Dist 
    FROM DoctorDeals, Doctors as Doc 
    WHERE DoctorDeals.DoctorID = Doc.ID 
    GROUP BY DealID) as T, 
    DoctorDeals, Deals, Doctors 
WHERE 
    T.Dist = Doctors.Distance 
AND 
    T.DealID = DoctorDeals.DealID 
AND 
    DoctorDeals.DoctorID = Doctors.ID 
AND 
    DoctorDeals.DealID = Deals.ID