我有一个如下所示的查询:
SELECT avg(round({$cohort1}/{$cohort2} * 100)) as overall_average,
`category`, `value`, {$cohort1},{$cohort2},`group`,
`quadrant`,round({$cohort1}/{$cohort2} * 100) as index_value
from {$table};
当我包含普通作品时,这并不完美。这只返回一行。我需要它来返回所有行。如果我删除平均值,那么一切都返回正常,但我没有计算平均值。我可以通过我的PHP中的单独查询得到这个。
但是,我意识到我需要根据队列的值推导出象限(字符串)的值。这些将是规则。问题是我不知道如何将它合并到我的查询中。
IF (the_value > overall_average and index_value > 100) THEN `quadrant` = "Priority One"
ELSEIF (the_value < overall_average and index_value > 100) THEN `quadrant` = "Potential"
ELSEIF (the_value > overall_average and index_value < 100) THEN `quadrant` = "Basics"
ELSEIF (the_value < overall_average and index_value < 100) THEN `quadrant` = "Ignore"
你能帮我提出一个完整的查询吗?如果这样做更简单,我也可以在从数据库返回数据后操作PHP中的数据。
答案 0 :(得分:1)
您可以使用CASE子句:
SELECT column1, column2, column2 as alias,...,
CASE
WHEN the_value > overall_average and index_value > 100 THEN 'Priority One'
...
WHEN another_condition THEN 'Potential'
...
ELSE 'default value'
END AS quadrant
FROM table
参考https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case