Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Multiple select count statements in one query

Tags:

sql

database

tsql

I have data with no relation. Just need to count various columns from 3 tables and display them on the page as a view.

This is the code so far but doesn't work:

SELECT COUNT(cars) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C,
 FROM tableCars
like image 808
user999690 Avatar asked Jun 28 '12 11:06

user999690


People also ask

How do I combine counts in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can we use 2 count 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.

Can we use count in select query?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).


2 Answers

SELECT A, B, C
FROM (SELECT COUNT(cars) as A FROM tableCars) a
CROSS JOIN (SELECT COUNT(boats) as B FROM tableBoats) b
CROSS JOIN (SELECT COUNT(trees) as C FROM tableTrees) c

should do it.

like image 197
Stuart Ainsworth Avatar answered Nov 09 '22 05:11

Stuart Ainsworth


Assuming you have a table like here (tableXxx tables having a field named xxx), your query had a syntax error by having a comma after AS C,, without that comma, it works properly (at least using sqlite, because mssql is not working at sqlfiddle for me):

http://sqlfiddle.com/#!5/5fa6c/3

SELECT COUNT(cars) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C
FROM tableCars

BTW, you could simplify your query to

SELECT (SELECT COUNT(cars ) FROM tableCars ) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C

The other answers are also perfect :)

like image 43
biziclop Avatar answered Nov 09 '22 07:11

biziclop