Home > OS >  Selecting Specified Results Without the Contain Value
Selecting Specified Results Without the Contain Value

Time:03-19

I've created a query that will provide me all instances that have an '(AB)' in the field_name column:

select distinct field_name, count(distinct field_id) as field_amounts
from data.table
where field_name like '%(AB)%'
group by field_name
order by field_amounts desc;

This would produce a result like:

field_name field_amounts
A (AB) 10
B (AB) 7

Now, I am looking to grab all the instances in the data set with the same exact field_names from this result but without the '(AB)' within the name. So, something like this:

field_name field_amounts
A 23
B 17

Any help would be appreciated. Thank you.

EDIT: To clarify, there are instances in the data that have '(AB)' and ones that don't. I want all the field names with '(AB)' but then also the ones that have the same field_names but without the '(AB)'. For example, if the entire data set looks like this:

field_name field_id
A (AB) 1
A 2
B (AB) 3
B 4
C 5
D (AB) 6
D 7

Then I would not want the field_name 'C' as there aren't any instances of 'C (AB)'. So, the new query I want would grab A, B, and D and count the instances.

CodePudding user response:

Try using the REPLACE function

CodePudding user response:

Just reverse the query by editting 3rd line as" where field_name not like '%(AB)%' "

CodePudding user response:

You can use aggregation and the condition in the HAVING clause:

SELECT TRIM(REPLACE(t.field_name, '(AB)', '')) field_name,
       COUNT(*) field_amounts
FROM tablename t
GROUP BY 1
HAVING SUM(t.field_name LIKE '%(AB)%') > 0;

See the demo.

  • Related