I have two tables with one to many relationship. I want to write a query which outputs all records from table with one record and only one record from the table having many records.
So the table having many records with first show the most occurring record. If there are equal occurrences then it will Order by ascending and show the first record.
Table1
Col1 Col2 Col3
a1 1 4
a2 2 5
a3 3 6
Table2
Col1 Col4
a1 10
a1 11
a1 22
a1 11
a2 10
a2 11
a3 19
a3 22
a3 22
a3 23
Query output:
Col1 Col2 Col3 Col4
a1 1 4 11
a2 2 5 10
a3 3 6 22
Hope I made it clear.
First you need to use a group by along with a min() to get the smallest number from table2, then you join to table1 to get the columns you need. I’ve used a left join as I’m assuming there may not be a match in table2 but you can change it to an
INNER JOINif there are always 1 or more corresponding records in table2.