每次求和后mysql求和结果

时间:2018-08-19 11:06:07

标签: mysql

你好,我试图将两个mysql结果的结果求和。

这是我的代码,不起作用。

SELECT 
     a.* ,
    b.* , 
    SUM(b.price) as price,
    SUM(b.tax) as tax,
    price + tax as price_tax --> error
FROM (SELECT  name , item_id 
     FROM items)a
LEFT JOIN (SELECT item_id , price , tax
         FROM bank
        )b
ON a.item_id = b.item_id 
GROUP BY item_id
  • 我想像这样对两个结果求和:price + tax as price_tax

1 个答案:

答案 0 :(得分:3)

第一

在执行特定查询期间,SQL引擎不知道select子句中的列别名,因此 您不能使用别名,您必须重复代码

      SELECT 

        SUM(b.price) as price,
        SUM(b.tax) as tax,
        SUM(b.price) +  SUM(b.tax) as  price_tax 
        FROM (
            SELECT  name , item_id 
            FROM items
        )a
        LEFT JOIN (
        SELECT item_id , price , tax

        FROM bank
        )b
        ON a.item_id = b.item_id 
        GROUP BY item_id

第二

在某些mysql版本中,不允许使用聚合功能,并选择group by中未提及的列,因此对于其他列,您必须删除group by中未提及的列(或添加假聚集功能)

      SELECT 
        a.item ,
        SUM(b.price) as price,
        SUM(b.tax) as tax,
        SUM(b.price) +  SUM(b.tax) as  price_tax 
        FROM (
            SELECT  name , item_id 
            FROM items
        )a
        LEFT JOIN (
        SELECT item_id , price , tax

        FROM bank
        )b
        ON a.item_id = b.item_id 
        GROUP BY item_id