HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Doing two counts on a single table in a single query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
querydoingtwosinglecountstable

Problem

There are some similar questions/answers on the forums but I think my problem is simpler.

I have two quesries, eg

SELECT count(*) FROM agent;
SELECT count(*) FROM agent WHERE active = 't';


I would like the output to be on a single row. For bonus points it would be nice to scan through the table only once and update both counters, to get a result like this

active_agents | total_agents
--------------+--------------
    10        |     20


So I guess I have two questions:

What is the Neatest/clearest way to do this, and

What is the fastest way to do it for very large tables.

Solution

You can use CASE statement for this scenario:

SELECT count(*) AS total_agents, 
       SUM(CASE WHEN active = 't' THEN 1 ELSE 0 END) AS active_agents
FROM Agent;


Sample execution with sample data:

CREATE TABLE Agent (Id INT, Active CHAR(10));

INSERT INTO Agent (Active)
VALUES ('a'), ('b'), ('t'), ('c'), ('t'), ('d');

SELECT count(*) AS total_agents, 
       SUM(CASE WHEN active = 't' THEN 1 ELSE 0 END) AS active_agents
FROM Agent;

Code Snippets

SELECT count(*) AS total_agents, 
       SUM(CASE WHEN active = 't' THEN 1 ELSE 0 END) AS active_agents
FROM Agent;
CREATE TABLE Agent (Id INT, Active CHAR(10));

INSERT INTO Agent (Active)
VALUES ('a'), ('b'), ('t'), ('c'), ('t'), ('d');

SELECT count(*) AS total_agents, 
       SUM(CASE WHEN active = 't' THEN 1 ELSE 0 END) AS active_agents
FROM Agent;

Context

StackExchange Database Administrators Q#177114, answer score: 7

Revisions (0)

No revisions yet.