MySQL使用计算的返回值来计算其他值

时间:2009-10-26 19:26:11

标签: sql mysql

假设我有一个带有以下内容的select语句:

SUM(st.tafPoints/200) as totalFriendReferrals,
SUM(CASE WHEN st.gender = "m" THEN st.tafPoints/200 ELSE 0 END) as maleFriendReferrals,
SUM(CASE WHEN st.gender = "f" THEN st.tafPoints/200 ELSE 0 END) as femaleFriendReferrals

我需要根据totalFriendReferrals计算maleFriendReferrals的百分比。这些都是派生的(即,最初不在列的列表中)值。所以,如果我尝试做类似的事情:

CONCAT( (maleFriendReferrals/totalFriendReferrals) *100 , '%') as malePercentReferrals

但是我收到了一个错误:

Unknown column 'maleFriendReferrals' in 'field list' – 1 ms

有没有办法轻松完成这项工作?我需要能够在查询本身内执行此操作,而不必遍历我的结果来计算百分比。

1 个答案:

答案 0 :(得分:3)

您应该将原始查询放入子查询

SELECT CONCAT( (maleFriendReferrals/totalFriendReferrals) *100 , '%') as malePercentReferrals
FROM
  (SELECT
    SUM(st.tafPoints/200) as totalFriendReferrals,
    SUM(CASE WHEN st.gender = "m" THEN st.tafPoints/200 ELSE 0 END) as maleFriendReferrals,
    SUM(CASE WHEN st.gender = "f" THEN st.tafPoints/200 ELSE 0 END) as femaleFriendReferrals
  FROM st) AS subquery