Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count 2 different data in one query

I need to calculate sum of occurences of some data in two columns in one query. DB is in SQL Server 2005.

For example I have this table:

Person: Id, Name, Age

And I need to get in one query those results:
1. Count of Persons that have name 'John'
2. Count of 'John' with age more than 30 y.

I can do that with subqueries in this way (it is only example):

SELECT (SELECT COUNT(Id) FROM Persons WHERE Name = 'John'), 
  (SELECT COUNT (Id) FROM Persons WHERE Name = 'John' AND age > 30) 
FROM Persons

But this is very slow, and I'm searching for faster method.

I found this solution for MySQL (it almost solve my problem, but it is not for SQL Server).

Do you know better way to calculate few counts in one query than using subqueries?

like image 331
Marek Kwiendacz Avatar asked Apr 02 '11 19:04

Marek Kwiendacz


People also ask

How do I COUNT multiple data in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table. The query to create a table is as follows.

How do you select two tables in a single query?

To retrieve information from more than one table, you need to join those tables together. This can be done using JOIN methods, or you can use a second SELECT statement inside your main SELECT query—a subquery.

How do I COUNT two distinct columns in SQL?

but when we want to count distinct column combinations, we must either clumsily concatenate values (and be very careful to choose the right separator): select count(distinct col1 || '-' || col2) from mytable; or use a subquery: select count(*) from (select distinct col1, col2 from mytable);


1 Answers

Using a CASE statement lets you count whatever you want in a single query:

SELECT
    SUM(CASE WHEN Persons.Name = 'John' THEN 1 ELSE 0 END) AS JohnCount,
    SUM(CASE WHEN Persons.Name = 'John' AND Persons.Age > 30 THEN 1 ELSE 0 END) AS OldJohnsCount,
    COUNT(*) AS AllPersonsCount
FROM Persons
like image 152
Chris Shaffer Avatar answered Oct 05 '22 20:10

Chris Shaffer