SQL:根据子查询结果更新列

时间:2012-01-20 20:47:34

标签: sql sql-server tsql

我有一个包含以下列的T-SQL表:Date,StationCode,HDepth和MaxDepth。默认情况下,MaxDepth列中的每一行都设置为0。我想要做的是找到按日期和StationCode的最大HDepth,并将MaxDepth更新为这些行上的列。我编写了一个SELECT语句来查找最大值出现的位置,它是:

SELECT StationCode, [Date], MAX(HDepth) AS Maximum FROM dbo.[DepthTable] GROUP BY [Date], StationCode

如何将此查询放入Update语句中,以便在此查询返回的行上将MaxDepth设置为1?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

UPDATE a
SET MaxDepth = 1
FROM dbo.[DepthTable] AS a
    JOIN (
        -- Your original query
        SELECT StationCode, [Date], MAX(HDepth) AS Maximum
        FROM dbo.[DepthTable]
        GROUP BY [Date], StationCode
    ) AS b ON a.StationCode = b.StationCode
        AND a.[DATE] = b.[DATE]
        AND a.HDepth = b.Maximum -- Here we get only the max rows

但是,如果列只是基于其他列,那么您可能会考虑将此逻辑放入视图中(以避免update anomalies)。这种视图的选择可能如下所示:

SELECT a.[Date], a.StationCode, a.HDepth,
    CASE WHEN b.Maximum IS NULL THEN 0 ELSE 1 END AS MaxDepth
FROM dbo.[DepthTable] AS a
    LEFT JOIN (
        -- Your original query
        SELECT StationCode, [Date], MAX(HDepth) AS Maximum
        FROM dbo.[DepthTable]
        GROUP BY [Date], StationCode
    ) AS b ON a.StationCode = b.StationCode
        AND a.[DATE] = b.[DATE]
        AND a.HDepth = b.Maximum -- Here we get only the max rows