如何从具有最新时间戳的JOIN中获取记录集?

时间:2014-05-09 17:00:35

标签: sql sql-server

我正在编写一个从3个表中获取一些数据的存储过程。现在,我的输出看起来像这样:

sql output

钻机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.

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

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
    , robinson_Rigs.rigName
    , robinson_Clients.companyName
    , robinson_Wells.wellName
    , robinson_Wells.county
ORDER BY robinson_Rigs.rigId

按聚合之前的所有内容进行分组。除非您通过

了解组,否则SQL不会很好用

答案 1 :(得分:1)

如果任何其他字段包含不同的装备值,则只需对除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

已加入的子查询将返回所有装配及其最大(最近)日期的列表。通过rigId和startDate将其连接到完整的robinson_rigs表将“过滤”表格,以便仅返回每个装备具有最新日期的记录。

相关问题