-1
\$\begingroup\$

I have a table called dfmt that lists the location, revenue and franchise. I want to find the franchise pairs that operate together in more than one location.

Some sample data

So far, I have a query that finds the franchise pairs that operate in the same location:

select T1.fr, T2.fr2 from dfmt T1 join (select fr as fr2, loc as loc2 from dfmt) as T2 on T1.fr < T2.fr2 and T1.loc = T2.loc2 order by loc;

I do not know how to go from here to find the franchise pairs that operate together in only more than one location.

Another query that may be useful that Finds the franchise that generates the maximum revenue in more than one location.

select fr, count(*) from tst2 where rev in (select max(rev) from tst2 group by loc) group by fr having count(*)>1;
enter code here
\$\endgroup\$
3
  • \$\begingroup\$ Hi @anon - not sure what the R has to do with it - perhaps remove it from the question and put in some sample data.. \$\endgroup\$
    – Mr R
    Commented Apr 8, 2021 at 21:47
  • \$\begingroup\$ Yes, I deleted it and put some sample data, please look at it again if you can help \$\endgroup\$
    – anon
    Commented Apr 8, 2021 at 22:05
  • \$\begingroup\$ "I do not know how to go from here" So the current code doesn't do yet what you want it to do? Please take a look at the help center. \$\endgroup\$
    – Mast
    Commented Apr 9, 2021 at 19:50

1 Answer 1

0
\$\begingroup\$

Something like this - use group by to gather all the "franchise pairs" and you count how many have locations..

SELECT X.fr, X.fr2, COUNT(X.loc) as count FROM 
(
  select T1.fr, T2.fr2, T1.loc from dfmt T1 join (select fr as fr2, loc as loc2 from dfmt) as T2 on T1.fr < T2.fr2 and T1.loc = T2.loc2
) AS X GROUP BY fr, fr2 HAVING count > 1;

NOTE: This relies on the inner query having distinct results - ie.. you can't have say "Best Western" and "Raddison" twice for the same location.

\$\endgroup\$
3
  • \$\begingroup\$ I recieve an error ERROR 1054 (42S22): Unknown column 'loc' in 'field list' \$\endgroup\$
    – anon
    Commented Apr 8, 2021 at 22:24
  • \$\begingroup\$ @anon I didn't look closely enough at your query (which I've used as a sub-query) to see it didn't have loc in the result [that data you show isn't the result of it !!]. I'll update the answer with that - however you may need to cater for DB differences ... \$\endgroup\$
    – Mr R
    Commented Apr 8, 2021 at 23:00
  • \$\begingroup\$ @anon ie. if your DB doesn't support HAVING - drop it and then do as another sub-query with a WHERE count > 1 \$\endgroup\$
    – Mr R
    Commented Apr 8, 2021 at 23:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.