views:

27

answers:

4

I've written SQL count statements before but I need to write a query which returns 2 sets of count values for a condition. The original query counts the amount of people for a company who have invalid information, fine, works great. I now need to extend this query so that it performs the above operation but also includes the total count of people.

So for instance, I'll get a result for Company A of 5 invalid people out of a total of 10.

I'm using a group by on my first query on company id.

Is it possible to include 2 count values?

Edit 1

Probably should have said, I'm using MySQL.

A: 

you'd need to have the invalid count in a case statement in the select clause instead of in the where clause

Beth
Ah that sounds practical, case statement?
see omg's example
Beth
+2  A: 

Without table structure, made assumptions:

  SELECT t.company_id,
         SUM(CASE WHEN t.isinvalid = 1 THEN 1 ELSE 0 END) AS numInvalid,
         COUNT(*) AS total
    FROM YOUR_TABLE t
GROUP BY t.company_id
OMG Ponies
A: 

depending on your RDBMS - there are different solutions. In SQL Server/Oracle - you can use OVER() clause.

http://msdn.microsoft.com/en-us/library/ms189461.aspx

Example:

select count(PersonID) over() as TotalCount, count(personID) over(PARTITION BY CompanyID) FROM Table

IMHO
I'd be using MySQL
@user275074: MySQL doesn't support analytic functions.
OMG Ponies
A: 

Figured this problem out doing a left join and counting based on those results.