问题
Newbie to SQL. Kindly help.
I need to count number of records which have a pattern in one of the fields, for multiple patterns. I know how to do it for one pattern, but how do I get count of each pattern when there are multiple patterns coming from a subquery. I am using Oracle. I will try to explain with an example.
SELECT count(*) FROM TableA
WHERE
TableA.comment LIKE '%world%';
Now this code will return the number of records which have 'world' anywhere in the TableA.comment field. My situation is, I have a 2nd query which has returns a list of patterns like 'world'.How do I get the count of each pattern ?
My end result should just be 2 columns, first column pattern, second column count_of_pattern.
回答1:
You can use like
to join the subquery to the table:
SELECT p.pattern, count(a.comment)
FROM (subquery here that returns "pattern"
) p left outer join
TableA a
on a.comment like '%'||p.pattern||'%'
group by p.pattern;
This assumes that the pattern
does not have wildcard characters. If it does, then you do not need to do the concatenation.
This also uses a left outer join
so that all patterns will be returned, even with no match.
来源:https://stackoverflow.com/questions/18049602/using-like-operator-with-a-subquery-that-returns-multiple-results