gpt4 book ai didi

mysql - 添加两个计算列以使用 "WHERE"子句进行查看

转载 作者:行者123 更新时间:2023-11-29 12:13:48 24 4
gpt4 key购买 nike

我使用它来创建一个 View ,其中包含表中的所有列以及一个新列,该新列的值基于其他两列的计算。我可以正常添加一列:

CREATE VIEW `calculated_full` AS
SELECT *,
`planned`-`actual_widget` AS `widget_delta` FROM `joined_table` where product = "widgets"

基本上,这意味着在这两列之间执行此计算,但前提是第三列(product)具有特定值。这工作得很好。

但是,我需要执行此操作以将另一个计算列添加到 View 中,仅当第三列 (product) 具有不同值时才应执行该计算列。就像这样(这当然行不通)。

CREATE VIEW `calculated_full` AS
SELECT *,
`planned`-`actual_widget` AS `widget_delta` FROM `joined_table` where product = "widgets",
`planned`-`actual_knob` AS `knobs_delta` FROM `joined_table` where product = "knobs"

最佳答案

我认为您希望按行执行计算,并且所有值都在同一个表中,如果是这样,您可以使用相当于 if 语句的 CASE 有选择地执行计算。声明。

当未找到案例时,将返回 null。

select *,
case when product = "widgets" then `planned`-`actual_widget` end as widget_delta,
case when product = "knobs" then `planned`-`actual_knobs` end as knobs_delta
from joined-table

如果你不想让它返回null,只需添加 ELSE子句:

case when condition then value_if_true else value_if_false end

CASE声明也可以这样写:

case product when "widget" then widgetvalue end

或者如果您需要多个案例:

case product
when "widget" then widgetvalue
when "knob" then knobvalue
else defaultvalue
end

关于mysql - 添加两个计算列以使用 "WHERE"子句进行查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com