I’ve been banging my head on this one. I think I’m close. (Oracle, SQL)
I’ve got a table that looks like the following.
Company Code
Apple A
Google A
Microsoft B
Apple C
Google B
Microsoft B
Apple C
Google C
Microsoft B
Each company can resolve to multiple codes.
What I want to do is create a SQL statement that for each company will give me the company with code that appears the most frequently. So in my example I’d get
Apple C
Google <nothing since there's no clear max>
Microsoft B
What I’ve put together so far is the following. This query returns to me the company with the code that appears the most, however if I have a tie between two codes for a company, I get both back. For Google in my example I’d get (Google, A), (Google, B), (Google, C). I want nothing returned.
I believe that I can join the whole thing again with itself and some additional where clauses to filter out the duplicate companies, however I was wondering if there is a better way to do this. What’s killing me is the aggregation functions along with the group by since sometimes I get an Oracle single-group group error. Any suggestions are appreciated.
SELECT m1, c.company sp1, b.code ul1 FROM
(SELECT MAX(c1) m1, company FROM
(SELECT COUNT(company||code) c1, company, code FROM table GROUP BY company, code ) a
GROUP BY company) c
left OUTER JOIN
(SELECT COUNT(company||code) c1, company, code FROM table GROUP BY company, code ) b
ON c.company=b.company and
m1=b.c1;
mj
you can do it with this:
breaking this down:
this gets us each company with their code count:
from this we want the most popular. we do this with an analyic:
giving:
but now if theres duplicates (as google has)..we count(*) the rows that have RN=1.
giving
so we need to say where RN=1 and also c = 1 (ie only ONE row had that number of recs. so we end up with:
ie rn = 1 and the c > 1 check is in the case at the top (as we don’t want to filter rows out, just mark them as ambiguous.