Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQL to compare counts of identifiers from two tables

I'm trying to construct a query that compares two tables with identical structure

Table 1:
ID | Data 

Table 2:
ID | Data

ID is a nonunique key (Data is repeatable but ID|Data combos are unique). I need a list of IDs where the COUNT of those IDs is greater in Table 2 than in Table 1.

So for example, if

Table 1
a | data
a | data1    
b | data2

Table 2
a | data
a | data1
b | data2
b | data3

would generate the output "b"

This feels like it should be easy, but my head is scrambled right now. I'm doing this in mysql if that affects options.

like image 841
Kyle Banerjee Avatar asked Feb 28 '13 19:02

Kyle Banerjee


People also ask

How can I compare two table values in SQL?

Compare Two Tables using UNION ALL Select * from ( Select Id_pk, col1, col2...,coln from table1, 'Old_table' Union all Select Id_pk, col1, col2...,coln from table2, 'New_tbale' ) cmpr order by Id_pk; The above query returns the all rows from both tables as old and new.

How do I compare two tables in SQL to find unmatched records?

Use the Find Unmatched Query Wizard to compare two tables One the Create tab, in the Queries group, click Query Wizard. In the New Query dialog box, double-click Find Unmatched Query Wizard. On the first page of the wizard, select the table that has unmatched records, and then click Next.

How do you compare values in two tables?

Compare two tables by using joins. To compare two tables by using joins, you create a select query that includes both tables. If there is not already an existing relationship between the tables on the fields that contain the corresponding data, you create a join on the fields that you want to examine for matches.

How do you compare results of two SQL queries?

By using UNION, UNION ALL, EXCEPT, and INTERSECT, we can compare two queries and get the necessary output as per our requirement. Given examples are simple to follow, we can have complex queries and can apply the mentioned constructs in them and can compare.


1 Answers

To get the count for each key,

select count(*) as count, ID from Table1 group by ID

So, use this as a sub-query in the from clause, and join the tables.

select tt1.ID
from (select count(*) as count, ID from Table1 group by ID) tt1
  inner join (select count(*) as count, ID from Table2 group by ID) tt2
     on tt1.ID = tt2.ID
where tt1.count < tt2.count
like image 72
Marlin Pierce Avatar answered Sep 17 '22 19:09

Marlin Pierce