[英]SQL selecting with conditioning from a subquery
I am trying to perform two sum functions from a query.我正在尝试从查询中执行两个求和函数。 However, I want to only perform one of the sum functions if it meets a certain condition without affecting the other sum function.
但是,我只想执行一个求和函数,如果它满足某个条件而不影响另一个求和 function。
What I was thinking is to use something similar to select x where condition = 1 from AC which is however not possible.我在想的是使用类似于 select x where condition = 1 from AC 但这是不可能的。
Here is the sample query where I want the second [sum(t.match)] selection to only calculate if the result in the subquery: match = 1 while still getting the total sum of all qqty.这是示例查询,我希望第二个 [sum(t.match)] 选择仅计算子查询中的结果是否为:match = 1,同时仍获得所有 qqty 的总和。
select
sum(t.qqty), sum(t.qqty)
from
(select
car, cqty, qqty,
case when cqty = qqty then 1 else 0 end as match,
location, state) t
Use conditional aggregation -- that is case
as the argument to the sum()
:使用条件聚合——即
case
作为sum()
的参数:
select sum(t.qqty), sum(case when condition = 1 then t.qqty else 0 end)
from t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.