[英]Group only if condition is met
I have a table with fields TYPES, AMOUNT and COMMENT 我有一个带有字段TYPES,AMOUNT和COMMENT的表
I want to group by the TYPES field, but if the 'TYPES' value is "other" AND 'COMMENT' is not empty, I want those records to show up separately. 我想按“类型”字段分组,但是如果“类型”值是“其他”并且“注释”不为空,我希望这些记录分开显示。
Example result: 结果示例:
+-----------+-----------+-----------+
| types | amount | comment |
+-----------+-----------+-----------+
| type1 | 27 | |
| type2 | 65 | |
| type3 | 45 | |
| other | 4 | blabla |
| other | 8 | something |
-------------------------------------
So instead of grouping the two "other" records, I want those records to show up separately (but only if they also have a comment) 因此,我不想将两个“其他”记录分组,而是希望这些记录分开显示(但前提是它们也要有注释)
If I understand correctly, you want all rows with a given type to grouped together unless the type is 'Other' and the comment is not NULL
. 如果我理解正确,则您希望将具有给定类型的所有行组合在一起, 除非类型为'Other'并且注释不是
NULL
。
A close approximation is: 近似为:
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);
The only issue is that rows with types = 'Other'
and the same comment will be grouped together. 唯一的问题是
types = 'Other'
和相同注释的行将被分组在一起。 To fix this correctly, you need a unique identifier on each row, which MySQL does not readily provide. 为了正确解决此问题,您需要在每一行上都使用唯一的标识符,而MySQL并不容易提供。
In your case I see two separate data sets. 在您的情况下,我看到两个单独的数据集。 Try with
union all
as below 尝试与
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.