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
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.
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.
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).
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With