[英]Group only if condition is met
我有一个带有字段TYPES,AMOUNT和COMMENT的表
我想按“类型”字段分组,但是如果“类型”值是“其他”并且“注释”不为空,我希望这些记录分开显示。
结果示例:
+-----------+-----------+-----------+
| types | amount | comment |
+-----------+-----------+-----------+
| type1 | 27 | |
| type2 | 65 | |
| type3 | 45 | |
| other | 4 | blabla |
| other | 8 | something |
-------------------------------------
因此,我不想将两个“其他”记录分组,而是希望这些记录分开显示(但前提是它们也要有注释)
如果我理解正确,则您希望将具有给定类型的所有行组合在一起, 除非类型为'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并不容易提供。
在您的情况下,我看到两个单独的数据集。 尝试与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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.