1

I'm trying to declare variables and calculate fields in MySQL Workbench with a specific data set. Here's an example of the data I'm pulling:

select
product.id as "Product ID",
product.name as "Product Name",
product.type as "Product Type",
product.weight as "Product Weight",
product.amount as "Product Amount",
product.cost as "Product Cost"

I have all of the appropriate joins below, but I'd like to create an additional variable that I can use to manipulate, and in this instance, declare it as "Total Cost". Total Cost however would be different based on the "Product Type". So if the Product Type was "variable", I would calculate the total cost as product (product.cost * product.weight), and if the Product Type was "fixed", I was calculate the total cost as (product.cost * product.amount).

Let me know if there's a way to build an IF function and declare it as a valueable before my joins.

Thanks!

Jeff

4

1 回答 1

1

您在子句中添加的任何WHERE内容也将过滤行数。所以这显然不是要走的路。如果您只想获得一个额外的值,该值将被计算并取决于您应该使用的其他字段的CASE语句。

select blah, blah, blah,
    case product.type
        when 'variable' then product.cost * product.weight
        when 'fixed' then product.cost * product.amount
    end TotalCost
from blah blah

此链接中的更多信息。

于 2013-09-17T01:07:10.190 回答