I want to write a SQL query that will find all the number of records in a table that are associated with the same child records.
For example:
In the dataset below parents 1001 and 1003 are associated with the same child records:
Parent ID | Child ID |
---|---|
1001 | C101 |
1001 | C102 |
1001 | C103 |
1002 | C201 |
1002 | C202 |
1002 | C203 |
1003 | C101 |
1003 | C102 |
1003 | C103 |
Expected Results
I want to see for each parent the number of other parent records that are associated with the same set of child records, like this:
Parent ID | Total with same child records |
---|---|
1001 | 1 |
1002 | 0 |
1003 | 1 |
I have tried various joins but unable to figure out a sensible solution. Ideas please, thanks.
2
Answers
For each parent, you want to build a list of children ids. In Oracle this would be the LISTAGG() function, but in MySQL it seems to be GROUP_CONCAT() (see Aggregate function in MySQL – list (like LISTAGG in Oracle) ). So something like
Once you have that, you can analyze it in a spreadsheet, or add a GROUP BY to count how many parents have the same set of children
You could use the
count
window function andgroup_concat
function as the following:see demo