0

I am new to SQL and I am trying to build a SQL query against a SQL Server CE 4 database that counts the same column (CompanyName) multiple times based off its Active status (0 or 1). I need the Total, Active and In Active by State. I think this is a subquery that for Total, Active and In Active, but am not sure how to build it.

Essentially I want to have a table that will provide a result like this based off the CompanyName.

State     Total Active InActive
Texas      10     6       4 
Florida    15     5       10

The basic query I have so far is

SELECT State, COUNT(CompanyName) AS Total
FROM  JobApps AS j
GROUP BY State
ORDER BY Total DESC

Any help is appreciated.

4

1 回答 1

3

SUM在同一个分组上,使用一个CASE语句:

SELECT State, COUNT(CompanyName) AS Total
, SUM(CASE Active WHEN 1 THEN 1 ELSE 0 END) AS Active
, SUM(CASE Active WHEN 1 THEN 0 ELSE 1 END) AS InActive
FROM  JobApps AS j
GROUP BY State
ORDER BY Total DESC
于 2013-06-02T22:06:53.913 回答