如何在mysql的单个列中将多个选择查询相加?

时间:2018-02-01 13:38:57

标签: mysql

如何在单列中对此查询求和。

    SELECT SUM(IFNULL(ih.amount,0.00)) AS amount 
      FROM human_resources hr 
      JOIN functions f 
        ON hr.function_id = f.id
      JOIN params_hours_cost phc 
        ON phc.function_id = f.id 
       AND phc.function_id = 2
      LEFT 
      JOIN mca_to_hrc ih  
        ON hr.id = ih.human_resource_id
      JOIN management_cost_action ia 
        ON ia.id = ih.mca_id
     WHERE ia.structure_id = 3 
       AND ia.year = 2018
       AND ia.status_id = 0; 

    SELECT SUM(IFNULL(ih.amount,0.00)) amount  
      FROM human_resources hr 
      JOIN functions f 
        ON hr.function_id = f.id
      JOIN params_hours_cost phc 
        ON phc.function_id = f.id 
       AND phc.function_id = 2
      LEFT 
      JOIN mca_to_thrc ih  
        ON hr.id = ih.human_resource_id 
       AND ih.mca_id = 2
      JOIN management_cost_action ia 
        ON ia.id = ih.mca_id
     WHERE ia.structure_id = 3
       AND ia.year = 208
       AND ia.status_id = 0; 

SELECT SUM(IFNULL(ie.distributed_amount,0.00)) distributed_amount  
  FROM revenue_and_expenses re 
  LEFT 
  JOIN mca_to_ee ie 
    ON re.id = ie.revenue_expenses_id
 WHERE re.transaction_type = 2 
   AND ie.amount > 0  
   AND re.year = 2018 
   AND re.structure_id = 3

1 个答案:

答案 0 :(得分:0)

将所有三个查询和SUM别名amount包裹起来。

distributed_amount更改为amount

修改年度错误2082018

SELECT SUM(a.amount) FROM (
SELECT SUM(IFNULL(ih.amount,0.00)) AS amount 
FROM human_resources hr INNER JOIN functions f ON(hr.function_id=f.id) 
INNER JOIN params_hours_cost phc ON(phc.function_id = f.id AND phc.function_id=2) 
LEFT JOIN mca_to_hrc ih ON(hr.id=ih.human_resource_id) 
INNER JOIN management_cost_action ia ON(ia.id=ih.mca_id)  
WHERE ia.structure_id = '3' 
AND ia.year='2018' 
AND ia.status_id='0'
UNION ALL
SELECT SUM(IFNULL(ih.amount,0.00)) AS amount  
FROM human_resources hr 
INNER JOIN functions f ON(hr.function_id=f.id) 
INNER JOIN params_hours_cost phc ON(phc.function_id = f.id AND phc.function_id=2) 
LEFT JOIN mca_to_thrc ih ON(hr.id=ih.human_resource_id AND ih.mca_id='2') 
INNER JOIN management_cost_action ia ON(ia.id=ih.mca_id)  
WHERE ia.structure_id = '3' 
AND ia.year='2018' 
AND ia.status_id=0
UNION ALL
SELECT SUM(IFNULL(ie.distributed_amount,0.00)) AS amount
FROM revenue_and_expenses re 
LEFT JOIN mca_to_ee ie ON(re.id=ie.revenue_expenses_id)  
WHERE re.transaction_type=2 
AND ie.amount>0  
AND re.year='2018' 
AND re.structure_id='3') a