简体   繁体   English

如何对两个SUM SQL求和?

[英]How to SUM result both SUMs SQL?

Using this query I try to sum result of both SUM function: 使用此查询,我尝试对两个SUM函数的结果求和:

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult,
SUM(result + noresult)
from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day`

I try to do that in this line: 我尝试在这一行中这样做:

SUM(result + noresult)

Try this: 尝试这个:

select 
    DAY(created_at) AS day, 
    SUM(if(status = '1', 1, 0)) AS result, 
    SUM(if(status = '2', 1, 0)) AS noresult,
    SUM(if(status in ('1', '2'), 1, 0)) 
from `clients` 
where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) 
group by `day`

You can't use alias in select columns name you must repeat the code 您不能在选择列名称中使用别名,而必须重复代码

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult,
SUM(if(status = '1', 1, 0)) + SUM(if(status = '2', 1, 0)) AS all_result

from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day`

you must repeat the code because the different SQL clause are processed in a specific order (first from then where then select and and group by .... etc.. ) so at the moment of the select parsing the alias are not available to the sql engine 您必须重复代码,因为不同的SQL子句是按照特定的顺序处理的(首先是从那里开始,然后是select和group by ....等。),因此在select解析时别名不能用于sql引擎

As several other people have stated, you cannot use aliases in your select statement. 正如其他几个人所述,您不能在select语句中使用别名。 However, to keep it cleaner, you could combine both conditions rather than summing both SUM fields. 但是,为了使其更整洁,您可以合并两个条件,而不是对两个SUM字段求和。

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult,
SUM(if(status = '1' OR status = '2', 1, 0)) AS newcolumn
from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day`

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

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