简体   繁体   中英

Group only if condition is met

I have a table with fields TYPES, AMOUNT and 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 .

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. To fix this correctly, you need a unique identifier on each row, which MySQL does not readily provide.

In your case I see two separate data sets. Try with union all as below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM