我在寫一個存儲過程,它從3個表中獲取一些數據。現在,我的輸出是這樣的:如何從包含最新日期戳記的JOIN抓取記錄集?
鑽機20列出了兩次。我只想抓取最新日期戳的記錄。所以我的查詢現在看起來是這樣的:
SELECT
robinson_Rigs.rigId
, robinson_Rigs.rigName
, robinson_Clients.companyName
, robinson_Wells.wellName
, robinson_Wells.county
, max(robinson_Wells.startDate)
, robinson_Wells.directions
FROM robinson_Wells
JOIN robinson_Rigs ON robinson_wells.rigId = robinson_Rigs.rigId
JOIN robinson_Clients on robinson_Wells.clientId = robinson_Clients.clientId
group by robinson_Rigs.rigId
ORDER BY robinson_Rigs.rigId
但我收到此錯誤:
Msg 8120, Level 16, State 1, Procedure robinson_GetAllDrivingDirections, Line 14
Column 'robinson_Rigs.rigName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我怎樣才能做到這一點?
這仍然會導致多個記錄被單個鑽機返回,因爲'startDate'不是唯一的值發生變化的字段。具有不同值的'Group By'子句中的任何字段都將導致返回一個額外的行。我也相信這會返回一個錯誤,因爲'方向'不包含在組中(並且該字段也至少在該示例中包含每個日期的不同值,導致第二行被返回用於鑽機20) 。 – Andrew