SELECT *,
SUM(
b1.bit_sum_excl * b1.bit_quantity -
if(b1.bit_deduction_percentage = 1, (b1.bit_deduction / 100)*(b1.bit_sum_excl * b1.bit_quantity), b1.bit_deduction)
) as _total_unconverted,
/*************** _total_unconverted * 0.15 as some_val; ****************/
FROM `bill_items` b1
LEFT JOIN clients_packing_list ON (b1.bit_cli_pack_list_id = clients_packing_list.cli_pack_list_id)
WHERE b1.bit_cli_bill_id = 1 OR b1.bit_cli_bill_id = 0
我希望能够添加表达式
_total_unconverted * 0.15 as _converted
进入选择。
目前它抱怨它不是专栏。
有没有办法做到这一点,还是我必须复制粘贴SUM代码并添加乘数?
答案 0 :(得分:0)
您可以在查询中使用user defined variables和MySQL。
SELECT *,
(@total:=SUM(
b1.bit_sum_excl * b1.bit_quantity -
if(b1.bit_deduction_percentage = 1, (b1.bit_deduction / 100)*(b1.bit_sum_excl * b1.bit_quantity), b1.bit_deduction)
)) as _total_unconverted,
(@total * 0.15) as _converted,
FROM `bill_items` b1
LEFT JOIN clients_packing_list ON (b1.bit_cli_pack_list_id = clients_packing_list.cli_pack_list_id)
WHERE b1.bit_cli_bill_id = 1 OR b1.bit_cli_bill_id = 0
编辑但是,这并不能保证以正确的顺序分配值。为了正确实现它,请参阅以下小例子:
SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
SELECT * FROM shop WHERE price=@min_price OR price=@max_price;
来自documentation的粘贴。
基本上,您首先分配值,然后根据值重新选择,以确保它们被正确分配。
答案 1 :(得分:0)
无法在返回该列的查询的_total_unconverted
列表中引用列别名SELECT
。
您可以将查询包装在一组parens中,并将其作为内联视图引用,并且列别名将在外部查询中可用。
在此示例中,内部查询返回列foo
,并且可以在外部查询中引用该列名:
SELECT v.foo
, v.foo * 0.15 AS bar
FROM ( SELECT SUM(col) AS foo FROM mytable ) v
但是它无法在内部查询的SELECT列表中引用foo
。 (MySQL确实允许在ORDER BY
子句和HAVING
子句中引用列别名。)
为避免内联视图的开销,您需要重复表达式。
SELECT *
, SUM(b1.bit_sum_excl * b1.bit_quantity -
IF(b1.bit_deduction_percentage = 1
,(b1.bit_deduction / 100)*(b1.bit_sum_excl * b1.bit_quantity)
, b1.bit_deduction
)
) AS _total_unconverted
, SUM(b1.bit_sum_excl * b1.bit_quantity -
IF(b1.bit_deduction_percentage = 1
,(b1.bit_deduction / 100)*(b1.bit_sum_excl * b1.bit_quantity)
, b1.bit_deduction
)
) * 0.15 AS some_val
FROM `bill_items` b1
LEFT
JOIN clients_packing_list
ON b1.bit_cli_pack_list_id = clients_packing_list.cli_pack_list_id
WHERE b1.bit_cli_bill_id IN (0,1)
答案 2 :(得分:0)
SELECT *,SOURCEQUERY._total_unconverted * 0.15 as some_val FROM
(
SELECT
SUM(
b1.bit_sum_excl * b1.bit_quantity -
if(b1.bit_deduction_percentage = 1, (b1.bit_deduction / 100)*(b1.bit_sum_excl * b1.bit_quantity), b1.bit_deduction)
) as _total_unconverted
FROM bill_items AS b1
LEFT JOIN clients_packing_list ON (b1.bit_cli_pack_list_id = clients_packing_list.cli_pack_list_id)
WHERE b1.bit_cli_bill_id = 1 OR b1.bit_cli_bill_id = 0
) AS SOURCEQUERY