【问题标题】:SQL Update statement, need help to pass the value to the subquerySQL Update 语句,需要帮助将值传递给子查询
【发布时间】:2013-07-14 13:48:06
【问题描述】:

这是我的 SQL 语句。它不工作。

UPDATE dbo.Smoothie
SET TotalCalories = (SELECT 
                        SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity / 100 
                                 ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity / 100 
                            END) AS calories
                     FROM dbo.SmoothieIngredients AS si
                     INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id
                     WHERE si.SmoothieId = SmoothieId  ---> i want to pass the SmoothieId from the main update statement to the subquery.
                    )

我试着给它起个名字 S2,还是不行。

UPDATE dbo.Smoothie as S2
SET S2.TotalCalories = (SELECT 
                           SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity / 100 
                                    ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity / 100 
                                END) AS calories
                        FROM dbo.SmoothieIngredients AS si
                        INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id
                        WHERE si.SmoothieId = S2.SmoothieId)

【问题讨论】:

    标签: sql-server sql-server-2008-r2 sql-update subquery


    【解决方案1】:

    您需要使用您的查询创建一个新表,然后将 TotalCalories 的值设置为列中的值。

    所以在这种情况下:

    UPDATE  dbo.Smoothie
    SET     TotalCalories = s2.calories
    FROM 
        ( SELECT    
             smoothieId,
             SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity / 100 
                                                ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity / 100 END) AS calories
             FROM      dbo.SmoothieIngredients AS si
             INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id
             GROUP BY SmoothieId
        ) AS s2
    WHERE dbo.Smoothie.Id = s2.smoothieId
    

    我的查询可能略有错误,但请注意查询 s2 表中的 Group By,然后将行与 Where 子句正常链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      相关资源
      最近更新 更多