简体   繁体   English

如何对两个 SUMmed SQL 结果字段求和

[英]How to SUM two SUMmed SQL result fields

I have a simple table structure holding records of reagent_bottles and reagent_aliquots .我有一个简单的表结构,用于保存试剂瓶试剂等分的记录。

Aliquots are created from bottles, and an aliquot record got a foreign key, bottle_id, to a bottles id.等分试样是从瓶子创建的,等分试样记录有一个外键,bottle_id,到瓶子 id。

To get the total volume of a particular reagent (counting both the volume in the bottles and the volume in the aliquots), the following query does the job, partly:要获得特定试剂的总体积(计算瓶子中的体积和等分试样中的体积),以下查询部分完成了这项工作:

SELECT  
      COALESCE(SUM(rb.volume), 0) AS bVolume, 
      COALESCE(SUM(ra.volume), 0) AS aVolume
FROM reagent_bottles AS rb
LEFT JOIN 
      reagent_aliquotes AS ra
ON rb.id = ra.bottle_id
WHERE reagent_id = 408;

returns for the above reagent id (408):返回上述试剂 ID (408):

bVolume | aVolume
       2|       6

Adding bVolume and aVolume, is the correct answer, ie 8. bVolume 和 aVolume 相加,是正确答案,即 8。

Question is, how do I re-write the above query to create a new field, total_volume , summing bVolume and aVolume within the query?问题是,如何重写上述查询以在查询中创建新字段total_volume 、求和 bVolume 和 aVolume ?

I tried this:我试过这个:

SELECT  
      COALESCE(SUM(rb.volume), 0) AS bVolume , 
      COALESCE(SUM(ra.volume), 0) AS aVolume, 
      SUM(bVolume + aVolume) AS total_volume
FROM 
      reagent_bottles AS rb
LEFT JOIN 
      reagent_aliquotes AS ra
ON rb.id = ra.bottle_id
WHERE reagent_id = 408;

but getting the error, Unknown column, bVolume in field list ..!但是在字段列表中收到错误,未知列,bVolume ..!

Sum the original columns:对原始列求和:

SELECT  
      COALESCE(SUM(rb.volume), 0) AS bVolume , 
      COALESCE(SUM(ra.volume), 0) AS aVolume, 
      SUM(COALESCE(rb.volume, 0) + COALESCE(ra.volume, 0)) AS total_volume
FROM 
      reagent_bottles AS rb
LEFT JOIN 
      reagent_aliquotes AS ra
ON rb.id = ra.bottle_id
WHERE reagent_id = 408;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM