7

I am currently trying to find distinct combinations within a table as two of the columns have a many to many relationship with each other.

The data is all around backup policies being run on against particularly clients and could be summarized as below:

enter image description here

The answer I would like to generate for the above table would be 7 as there are that number of distinct combinations.

Has anyone got an idea of how this might be done? I have tried experimenting with nested counts and distinct values (where I was able to filter to one column but not both).

TheGrew
  • 73
  • 1
  • 1
  • 4

2 Answers2

6

You can count distinct elements by running:

select count(distinct policy_id, client_id) from policy_client;

Another option would be to group by and count that:

select count(*) from (select policy_id, client_id from policy_client group by 1,2) a;

Run both version and see which one performs better on your dataset.

A very quick way but not totally accurate if you have a key on (policy_id and client_id) you can also check the cardinality of that index but that's an approximate not exact number.

oNare
  • 3,231
  • 2
  • 22
  • 35
Károly Nagy
  • 3,080
  • 1
  • 14
  • 13
3

I think the simplest would be:

SELECT COUNT(DISTINCT policy, client) 
         AS distinct_combinations
FROM table_name ;
ypercubeᵀᴹ
  • 99,450
  • 13
  • 217
  • 306