Skip to content
Advertisement

Generate Result based on max count in secondary column after a join

I have two tables which have a common key between them, and quite a lot of other important infos ; for the sake of simplicity i will be using Combination A and Combination B. When a combination is met, whichever table has the maximum number of records should be the source where i collect the information ; in this case say IDs. The priority when counts are same is Table1.

COMMONKEY column is the combination/join condition in my tables.

Updated Image :

( the image shows a screenshot of the trail data in an excel; The Requirement and Strategy are color mapped to make it quickly understandable )

I need to generate the result set using SQL as follows :

When table1.commonkey = table2.commonkey hits, I need to-

  • If table1 has 10 IDs, table2 has 5 IDs -> Pick 10 IDs from table1.
  • If table1 has 15 IDs, table2 has 30 IDs -> Pick 30 IDs from table2.
  • If table1 has 4 IDs, table2 has 4 IDs -> Pick 4 IDs from table1. ( when equal, choose table1 IDs )
  • When no matches occur with the common key, prevent a cross join and add in the rowsets linearly to the result table.

Edit : I’ve initially gone on routes with

to achieve workarounds with A-B or B-A result sets but both these approaches were quite wrong. Gathering Delta sets or Exclusion sets didnt go well.

Advertisement

Answer

Here’s one option; see comments within code


which results in

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement