使用同一表中具有不同条件的同一列的其他值更新一个表的值

时间:2014-10-24 13:36:28

标签: sql sql-server

有人可以帮忙吗?

我有一个包含2 SiteID不同值的表格,我正在尝试用同一个表格中的另一个值替换一个sited id。我想要site id =158时的值{ site id =56

时的值

结果1:Site id =158

Dt           C-Id  M-Id    Values
01/03/2014  14354   6   25504.3047
01/03/2014  15266   6   25504.3047
01/03/2014  14354   10  25504.3047
01/03/2014  14354   15  25504.3047
01/03/2014  15266   15  25504.3047
01/03/2014  14354   16  25504.3047

结果2:Site id = 56

Dt          C-Id   M-Id Values
01/03/2014  14354   6   11915
01/03/2014  15266   6   536
01/03/2014  14354   10  1517
01/03/2014  14354   15  3662
01/03/2014  15266   15  1071
01/03/2014  14354   16  3662

我写了这个查询:

UPDATE [WorkDb].[dbo].[M_values]
SET [value] = (
        SELECT O.[value]
        FROM [WorkDb].[dbo].[M_values] AS O
        WHERE O.siteid IN (56)
            AND O.DATE = '2014-03-01'
            AND O.C - Id IN (14354, 15266)
            AND O.M - Id IN (6, 10, 15, 16, 25, 55, 56, 18)
            AND ISNULL(O.value, 0) <> 0
        )
WHERE (
        siteid IN (158)
        AND DATE = '2014-03-01'
        AND C - Id IN (14354,15266)
        AND M - Id IN (6,10,15,16,25,55,56,18)
        AND ISNULL(value, 0) <> 0
        )

此查询返回错误:

Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

1 个答案:

答案 0 :(得分:0)

问题在于您没有加入正确的标准来获取单个记录。

UPDATE mv
SET [value] = site56.[value]
FROM [WorkDb].[dbo].[M_values] mv
INNER JOIN (
    SELECT O.[value],O.[date],O.[C-Id],O.[M-Id]
    FROM [WorkDb].[dbo].[M_values] as O
    WHERE O.siteid IN (56)
    and ISNULL(O.value,0)<>0
) site56 ON site56.[date]=mv.[date] AND site56.[C-Id]=mv.[C-Id] AND site56.[M-Id]=mv.[M-Id]
WHERE (
    mv.siteid IN (158)
    AND mv.[date] = '2014-03-01'
    and mv.[C-Id] IN (14354,15266)
    and mv.[M-Id] IN (6,10,15,16,25,55,56,18)
    and ISNULL(mv.[value],0)<>0
)