仅在满足条件时分组

Group only if condition is met

我有一个 table,其中包含字段 TYPES、AMOUNT 和 COMMENT

我想按 TYPES 字段分组,但如果 'TYPES' 值为 "other" 并且 'COMMENT' 不为空,我希望这些记录单独显示。

示例结果:

+-----------+-----------+-----------+
| types     | amount    | comment   |
+-----------+-----------+-----------+
| type1     |     27    |           |
| type2     |     65    |           |
| type3     |     45    |           |
| other     |     4     | blabla    |
| other     |     8     | something |
-------------------------------------

所以我不想将这两个 "other" 记录分组,而是希望这些记录单独显示(但前提是它们也有评论)

在你的例子中,我看到了两个独立的数据集。尝试使用 union all 如下

select types, amount,comment 
from tab
where (types = 'other' and comment is not null)
or types <> 'other'
group by types 
union all
select types, amount,comment  
from tab
where types = 'other'
and comment is null

如果我理解正确,您希望所有具有给定类型的行组合在一起除非类型是'Other'并且注释不是NULL .

近似值是:

select types,
       (case when types = 'Other' and comment is not null
             then comment end) as comment,
       sum(amount) as amount
from table t
group by types, 
         (case when types = 'Other' and comment is not null
               then comment end);

唯一的问题是具有 types = 'Other' 相同 注释的行将被组合在一起。要正确解决此问题,您需要在每一行上有一个唯一的标识符,MySQL 不容易提供。