SELECT COUNT(*) FROM Table1 WHERE user = "carl" AND ans = "yes"
then i want to divide the output of this query to another query, for example the output is 10. so it will be like:
10 / SELECT COUNT(*) From Table1 WHERE user = "carl"
How is the right syntax for this?
Thank You
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.
COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.
SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.
You can do this by running the two queries as sub-queries:
SELECT
(SELECT COUNT(*) FROM Table1 WHERE user = "carl" AND ans = "yes") /
(SELECT COUNT(*) From Table1 WHERE user = "carl")
Do a
SELECT (10/COUNT(*)) AS `myVariable` FROM `Table1` WHERE...
Then use your myVariable
as you need.
You want to use conditional aggregation and division. You don't need two queries:
SELECT SUM(ans = 'yes')/COUNT(*)
FROM Table1
WHERE user = 'carl';
The SUM(ans = 'yes')
counts the number of rows with yes
. Actually, you could further simplify this to:
SELECT avg(ans = 'yes')
FROM Table1
WHERE user = 'carl';
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