[英]Mysql group and sum based on condition
有没有一种方法可以根据条件对列进行分组和求和?
id | code | total | to_update
1 | A1001 | 2 | 0
2 | B2001 | 1 | 1
3 | A1001 | 5 | 1
4 | A1001 | 3 | 0
5 | A1001 | 2 | 0
6 | B2001 | 1 | 0
7 | C2001 | 11 | 0
8 | C2001 | 20 | 0
在此示例中,我想对所有共享同一code
行进行分组和求和,其中至少一行的to_update
值为1。按code
列分组,按total
。
上面的示例将导致:
code total
A1001 12
B2001 2
您需要有一个子查询,该子查询为您提供所有具有至少1条记录的代码,其中update = 1,并且您需要将其重新连接到表中并按和求和:
select m.code, sum(total)
from mytable m
inner join (select distinct code from mytable where `to_update`=1) t on m.code=t.code
group by m.code
或者,您也可以对to_update列求和,并进行过滤以使具有:
select m.code, sum(total)
from mytable m
group by m.code
having sum(to_update)> 0
您可以这样做:
SELECT code, SUM(total) AS total
FROM mytable
GROUP BY code
HAVING MAX(to_update) = 1
假设to_update的可能值为0或1。
在此小提琴中实现,根据问题的要求输出结果。
由于此查询仅扫描表一次,因此其性能比进行联接的解决方案更好。
您可以通过多种方式获得结果。 一种方法是获取具有to_update = 1
的code
值,然后可以使用它来获取total
的sum
。 可以通过几种不同的方法来完成此操作-一种方法是使用您要加入的子查询:
select
t1.code,
sum(total) as Total
from yourtable t1
inner join
(
select distinct t.code
from yourtable t
where t.to_update = 1
) t2
on t1.code = t2.code
group by t1.code;
或者,您可以使用where exists
的where exists
过滤掉行:
select
t1.code,
sum(total) as Total
from yourtable t1
where exists (select 1
from yourtable t2
where t2.to_update = 1
and t1.code = t2.code)
group by t1.code;
请参见带有两个版本的Demo的SQL Fiddle 。 无论哪种方式,您都需要基于to_update
值过滤行,然后对其进行汇总。
使用此查询:
SELECT
a.code,
a.total
FROM
(SELECT all
code as code,
sum(total) as total,
sum(`sum`.`update`) as status
FROM `Test`.`sum`
GROUP BY code) as a
WHERE a.status <> 0;
你有:
A1001 12
B2001 2
进行更新以使其状态不同于0就足够了。
问候
您可以使用in子句选择具有to_update = 1值的代码列表,然后使用group by子句获取总数
select code,sum(total) as total from sample
where code in (select distinct code from sample where to_update=1)
group by code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.