[英]MySQL - SELECT default value if null
Here's my query that I'm working with:这是我正在使用的查询:
SELECT (COUNT(`pass` = 0) / COUNT((`pass` = 0) + (`pass` = 1))) AS `PassRate` from `quiz_results`
Where I'm trying to get a percentage of people who have passed the quiz, however the issue is that if nobody as passed the quiz, then NULL
is returned.我试图获得通过测验的人的百分比,但问题是如果没有人通过测验,则返回
NULL
。 I'm trying to figure out how to return 0
in the event of NULL
.我试图弄清楚如何在
NULL
的情况下返回0
。
I've tried using ISNULL
however I didn't have any luck.我试过使用
ISNULL
但我没有任何运气。
The other issue I'm running into is that if nobody has failed the quiz, the value is always zero.我遇到的另一个问题是,如果没有人未通过测验,则该值始终为零。 So my two problems are as follows:
所以我的两个问题如下:
COUNT(
pass =0)
returns 0.COUNT(
pass =0)
返回 0 时返回 100。 Unfortunately I'm not all that great with SQL and I'm a bit stumped.不幸的是,我对 SQL 并不是那么好,而且我有点难住了。 I'm accessing MySQL through PHP.
我正在通过 PHP 访问 MySQL。 I added that in here, because I don't know if it changes anything.
我在这里添加了它,因为我不知道它是否会改变任何东西。
I'm using The SQL installed with XAMPP (Comes with PhpMyAdmin)我正在使用随 XAMPP 一起安装的 SQL(PhpMyAdmin 附带)
First, you don't want COUNT()
, you want SUM()
:首先,你不想要
COUNT()
,你想要SUM()
:
SELECT (SUM(`pass` = 0) / SUM((`pass` = 0) + (`pass` = 1))) AS `PassRate`
FROM `quiz_results`
The expressions COUNT(pass = 0)
and COUNT(pass = 1)
always return exactly the same number, and this is equivalent to COUNT(pass)
.表达式
COUNT(pass = 0)
和COUNT(pass = 1)
总是返回完全相同的数字,这相当于COUNT(pass)
。 COUNT()
is just looking at whether or not the expression is NULL
. COUNT()
只是查看表达式是否为NULL
。
Then, you can replace this with AVG()
, probably:然后,您可以将其替换为
AVG()
,可能是:
SELECT AVG(pass = 0) -- Should this be `pass = 1` ?
FROM quiz_results;
And, if you still get unwanted NULL
values:而且,如果您仍然得到不需要的
NULL
值:
SELECT COALESCE(AVG(pass = 0), 0) -- Should this be `pass = 1` ?
FROM quiz_results;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.