如何在查询中对别名字段求和

时间:2015-03-21 18:22:20

标签: php mysql sql join

我在下面有一个查询

SELECT  s.reference_no as rno , a.id, a.product_name, a.sale_id, s.id as sale,
        count(CASE WHEN b.id = 1 THEN b.name ELSE NULL END) as tax1,
        count(CASE WHEN b.id = 2 THEN b.name ELSE NULL END) tax2,
        count(CASE WHEN b.id = 3 THEN b.name ELSE NULL END) tax3,
        count(CASE WHEN b.id = 4 THEN b.name ELSE NULL END) tax4,
        count(CASE WHEN b.id = 5 THEN b.name ELSE NULL END) tax5,

       sum(CASE WHEN b.id = 1 THEN a.val_tax ELSE NULL END) sum1,
       sum(CASE WHEN b.id = 2 THEN a.val_tax ELSE NULL END) sum2,
       sum(CASE WHEN b.id = 3 THEN a.val_tax ELSE NULL END) sum3,
       sum(CASE WHEN b.id = 4 THEN a.val_tax ELSE NULL END) sum4,
       sum(CASE WHEN b.id = 5 THEN a.val_tax ELSE NULL END) sum5

FROM    sale_items a
        INNER JOIN tax_rates b
            ON a.tax_rate_id = b.id
         JOIN sales s ON s.id = a.sale_id   
GROUP   BY s.id
order BY sale desc

我想要一个额外的coloumn grandtotal_tax(sum1 + sum2 + sum3 + sum4 + sum5)。但是当我尝试它时会抛出错误未知列' total_tax_sum1'在'字段列表' 。那么如何总结别名字段。您可以找到我的三个表数据库模式here

1 个答案:

答案 0 :(得分:1)

您无法在定义它的select中使用别名。简单地说:

sum(case when b.id in (1, 2, 3, 4, 5) then a.val_tax end) as grandtotal_tax

请注意,else NULL是多余的,因为NULLcase语句中没有匹配项的值。

此外,如果b.id只能使用这五个值,则可以简化为:

sum(a.val_tax) as grandtotal_tax