Using 'LIKE' operator with a subquery that returns multiple results

久未见 提交于 2019-12-24 01:14:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!