使用Case时'SubQuery返回多行'

时间:2015-11-04 09:39:52

标签: mysql case

当他们有两个成年人和一个孩子进行预订时,我似乎很难给用户打折......输出文字说明如标题所示。虽然我知道这个问题,但我不确定如何解决它以使结果更加独特。

作为参考,价格来自不同的表格,但其他一切都在预订中。

任何帮助表示感谢并提前致谢

UPDATE BOOKING SET TotalCost=
(SELECT SUM(

CASE WHEN NumAdults = 2 AND NumChilds = 1 THEN
(NumAdults*(SELECT Cost FROM prices WHERE AgeType = 'Adult'))
+
(NumChilds*(SELECT Cost FROM prices WHERE AgeType = 'Child' / 2))


ELSE
(NumAdults*(SELECT Cost FROM prices WHERE AgeType = 'Adult'))
+
(NumChilds*(SELECT Cost FROM prices WHERE AgeType = 'Child'))
END
))
WHERE BookID  = 1

2 个答案:

答案 0 :(得分:2)

基本修复是在子查询中执行SUM: -


    {"rsBody":
     [{"productId":11,
    "productImageUrl":"http:xxxx"},
    {"productId":9,
    "productImageUrl":"http:"xxxx"}]}

但是如果我们能够看到表格描述和一些示例数据,那么不相信没有更好的方法来完成整个查询

例如,如果每个成人和儿童的价格都是唯一的,那么就可以这样做: -

UPDATE BOOKING SET TotalCost=
(
    CASE 
        WHEN NumAdults = 2 AND NumChilds = 1 
        THEN
            (NumAdults * (SELECT SUM(Cost) FROM prices WHERE AgeType = 'Adult'))
            +
            (NumChilds * (SELECT SUM(Cost) FROM prices WHERE AgeType = 'Child' / 2))

        ELSE
            (NumAdults * (SELECT SUM(Cost) FROM prices WHERE AgeType = 'Adult'))
            +
            (NumChilds * (SELECT SUM(Cost) FROM prices WHERE AgeType = 'Child'))
    END
)
WHERE BookID  = 1

答案 1 :(得分:1)

所有出现(NumAdults*(SELECT Cost FROM prices WHERE AgeType = 'Adult')

应为(NumAdults*(SELECT SUM(Cost) FROM prices WHERE AgeType = 'Adult')

您将Numadultsresultset相乘。

希望这有帮助