Mysql组和基于条件的求和

Mysql组和基于条件的求和,mysql,sql,Mysql,Sql,是否有一种基于条件对列进行分组和求和的方法 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

是否有一种基于条件对列进行分组和求和的方法

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\u update=1
code
值,然后您可以使用它来获取
总计的
和。这可以通过几种不同的方式来实现-一种是使用您加入的子查询:

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
筛选出行:

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;
请参阅两个版本的示例。无论哪种方式,您都需要根据
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;
有一个状态不同于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

预期结果对这些代码求和,其中至少有一条记录的更新值为1,这与您描述任务的方式相反。那么,哪个版本是正确的?是的,其中至少有一条记录具有更新值。我将尝试重写,但这是我的意图。这有点过分了,您不需要对此进行子查询,只需进行筛选即可。我们在
内部联接
查询上也有相同的想法。
select code,sum(total) as total from sample 
where code in (select distinct code from sample where to_update=1) 
group by code