Skip to content
Advertisement

How to calculate a non-inflated count from a denormalized table

Suppose I have a denormalized table that includes an ID and a value that I need to count. Something like this:

In this case, select Tree_ID, count(Count_If_True) from Table group by Tree_ID would show:

But If I denormalize my table further with a join from an Apples table (where every tree has multiple apples), it would look something like this:

This would inflate our count to:

Is there a simple way (without a CTE, for example) to write a single query to get back the original count result before Apple_IDs were introduced?

Advertisement

Answer

You need a distinct row identifier in the first table — perhaps that is among the other columns. It can be one or more columns. Then you can use count(distinct):

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