Skip to content
Advertisement

SQL count number of records in one set of data compared to another and present as a percentage

I would like to count the number of unique records not matching on 2 key variables from Data B compared to Data A and present the result as a percentage of the total unique records in Data B.

The code I have is as follows:

From the above data I expect to get the result of 1 / 4 where the numerator represents the (2, d) value from data B that doesn’t exist in data A and the denominator is the unique records by key in Data B. The code currently doesn’t work now I’ve put DISTINCT in, so I’m a bit lost.

Advertisement

Answer

Assuming that DataA does not contain duplicate rows, you must do a LEFT join of DataB to DataA and aggregate:

If DataA may contain duplicate rows, then:

See the demo (for MySql but it is standard SQL).
Result:

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