Skip to content
Advertisement

How to find these master records whose totals are not accurate

I have two tables (master-details relationship). The master table has a column (called total) recording the number of details records for the same master record. Having this column is for the performance reason). Here are the table specs:

table: MySum
column: id
column: total (total of MyDetail records for the same MySum record)

table: MyDetail
column: name
column: MySum

Because deletion of details records, the total in the master table may not be correct and so I would like to find these master records whose totals are not accurate. Here is the SQL I have. However, it generates zero records and I know this is not right based on the actual data.

select s.id, s.total from MySum s where s.total <> (select count(*) from MyDetail d where s.id = d.MySum group by d.MySum)

What is the right SQL statement?

I am using MS SQL Server and database-specific statement is okay for me. However, generic statement would be better.

Advertisement

Answer

If you want to do the calculation in the where, you can. You just need only the correlated subquery rather than a group by:

select s.id, s.total
from MySum s
where s.total <> (select count(*)
                  from MyDetail d
                  where s.id = d.MySum
                 );

EDIT:

If you want the count, then use a join and group by:

select s.id, s.total, d_cnt
from MySum s left join
     (select d.MySum, count(*) as d_cnt
      from MyDetail d
      group by d.MySum
     ) d
     on s.id = d.MySum
where s.total <> d_cnt or not (s.total = 0 and d_cnt is null);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement