Ask the Expert

SQL counts for separate related tables

I need statistics with count operation for more than two tables:

(select count(*) from T2 where ) 
   as totbooks , 
(select count(*) from T3 where 
      and descr like '%newspaper%' ) 
   as totnewspaper 
group by T1.description

    Requires Free Membership to View

This is similar to a recent question, Number of rows in two tables (24 May, 2007).

The difference here is that the counts have to be counts of related rows. You were quite right to use correlated subqueries to achieve the counts. However, your GROUP BY is both wrong (because it does not contain the non-aggregate city column that's in the SELECT clause) and unnecessary. Here's what your query should look like:

     , ( select count(*) 
           from T2 
          where id = ) as totbooks 
     , ( select count(*) 
           from T3 
          where id = 
            and descr like '%newspaper%' ) 
                             as totnewspaper 
  from T1

Notice that there is no GROUP BY. The subqueries effectively achieve the "grouping" and each returns a single value to the outer query.

This was first published in June 2007

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: