Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

divide by count result in mysql

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

like image 275
sleepsleepsleep90731 Avatar asked Jan 21 '14 22:01

sleepsleepsleep90731


People also ask

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

Can I do a sum of a count in MySQL?

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.

Can we use count in where clause in MySQL?

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.


3 Answers

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")
like image 68
Ike Walker Avatar answered Oct 05 '22 14:10

Ike Walker


Do a

SELECT (10/COUNT(*)) AS `myVariable` FROM `Table1` WHERE...

Then use your myVariable as you need.

like image 32
Andre Polykanine Avatar answered Oct 03 '22 14:10

Andre Polykanine


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';
like image 29
Gordon Linoff Avatar answered Oct 04 '22 14:10

Gordon Linoff