3つのテーブルからいくつかのデータを取得するストアドプロシージャを作成しています。現在、私の出力は次のようになっています。
リグ20は2回リストされています。最新の日付スタンプのあるレコードのみを取得したいと思います。したがって、私のクエリは次のようになります。
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以外のすべてをグループ化するだけで、他のフィールドにリグの異なる値が含まれている場合でも、リグの複数の行が返されます。
代わりに、次のようなものを試してください。
SELECT
robinson_Rigs.rigId
, robinson_Rigs.rigName
, robinson_Clients.companyName
, robinson_Wells.wellName
, robinson_Wells.county
, robinson_Wells.startDate
, robinson_Wells.directions
FROM robinson_Wells
JOIN robinson_Rigs ON robinson_wells.rigId = robinson_Rigs.rigId
JOIN
(
SELECT rigId
, MAX(startDate) AS MostRecentDate
FROM robinson_rigs
GROUP BY rigId
) latestRigDate ON robinson_Rigs.RigId = latestRigDate.RigId
AND robinson_rigs.StartDate = latestRigDate.MostRecentDate
JOIN robinson_Clients on robinson_Wells.clientId = robinson_Clients.clientId
ORDER BY robinson_Rigs.rigId
結合されたサブクエリは、すべてのリグIDとその最大(最新)日付のリストを返します。これをrigIdとstartDateによって完全なrobinson_rigsテーブルに結合すると、テーブルが「フィルタリング」され、各リグの最新の日付のレコードのみが返されます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加