在SELECT语句的其他列中使用别名

时间:2012-08-29 06:11:17

标签: mysql select alias

我希望在我的SELECT查询和列...

上做一些基本的数学运算
SELECT Rider, 
COUNT(if(Result = 1, Result, NULL)) AS "Firsts", 
COUNT(if(Result = 2, Result, NULL)) AS "Seconds", 
COUNT(if(Result = 3, Result, NULL)) AS "Thirds", 
COUNT(if(Result = " ", Result, NULL)) AS "NP",
COUNT(*) AS "Total",
"Firsts"/"Total"*100 AS "S/R"
FROM meeting_master
WHERE RaceDayDate>="2012-01-01"
GROUP BY meeting_master.Rider
ORDER BY Firsts DESC
LIMIT 100

我的问题(以及缺乏MySQL知识)是让S/R列计算第7行的数学...

1 个答案:

答案 0 :(得分:3)

您不应在SELECT中使用别名,如下所示:

"Firsts"/"Total"*100 AS "S/R"

而是像这样直接计算:

COUNT(if(Result = 1, Result, NULL))/COUNT(*) * 100 AS "S/R"

所以你的查询应该是:

SELECT Rider, 
COUNT(if(Result = 1, Result, NULL)) AS "Firsts", 
COUNT(if(Result = 2, Result, NULL)) AS "Seconds", 
COUNT(if(Result = 3, Result, NULL)) AS "Thirds", 
COUNT(if(Result = " ", Result, NULL)) AS "NP",
COUNT(*) AS "Total",
COUNT(if(Result = 1, Result, NULL))/COUNT(*) * 100 AS "S/R"
FROM meeting_master
WHERE RaceDayDate>="2012-01-01"
GROUP BY meeting_master.Rider
ORDER BY Firsts DESC
LIMIT 100

Just see SQLFiddle example here.