如何根据两个不同的列计算列?

时间:2013-12-12 00:29:19

标签: mysql sql

我需要创建一个名为weight的列,通过将歌曲播放的总次数乘以歌曲的唯一计数来计算。这就是我所拥有的:

SELECT music_id, 
COUNT(*) as count, 
COUNT(distinct user_id) as unique_count,
count * unique_count as weight

FROM plays GROUP BY music_id ORDER BY weight DESC LIMIT 50

我一直收到错误“字段列表中的未知列'计数'”,但是当我删除“count + unique_count as weight”并按常规计数排序时,该函数有效。

1 个答案:

答案 0 :(得分:1)

你能试试吗?

SELECT music_id, 
COUNT(*) as cnt, 
COUNT(distinct user_id) as unique_count,
COUNT(*) * COUNT(distinct user_id) as weight
FROM plays
GROUP BY music_id
ORDER BY weight DESC LIMIT 50

OR

SELECT music_id, cnt * unique_count AS weight 
FROM (
    SELECT music_id, 
    COUNT(*) as cnt, 
    COUNT(distinct user_id) as unique_count
    FROM plays GROUP BY music_id
) AS tab
ORDER BY weight DESC LIMIT 50

ALIAS ed列名称无法在同一级别引用。 e.g。

mysql> select name AS alias1, alias1 * 10 from test;
ERROR 1054 (42S22): Unknown column 'alias1' in 'field list'
mysql> select name AS alias1 from test where alias = '10';
ERROR 1054 (42S22): Unknown column 'alias' in 'where clause'