开发者

SQL - counting based on multiple criteria

开发者 https://www.devze.com 2023-01-21 01:01 出处:网络
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 invali

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 o开发者_JS百科peration 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.


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消