所以说我有一个像这样的mysql语句:
SELECT username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`, `top5`, `top3
FROM
(
SELECT username,
SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) `3rd places`,
SUM(CASE WHEN rating < 6 THEN 5 ELSE 0 END) `top5`,
SUM(CASE WHEN rating < 4 THEN 5 ELSE 0 END) `top3`
FROM Table1
GROUP BY username
ORDER BY `1st places` DESC
) q, (SELECT @n := 0) n
如何在这个sql语句中添加我创建的名为'1st places'+'2nd places'+'3rd places'的列,并创建另一个名为“total finish”的列?看起来很简单,但我似乎无法弄明白。
答案 0 :(得分:1)
您可以将它们添加到一起,并为该额外列提供别名: -
SELECT username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`, `top5`, `top3, `1st places` + `2nd places` + `3rd places` AS `total finishes`
FROM
(
SELECT username,
SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) `3rd places`,
SUM(CASE WHEN rating < 6 THEN 5 ELSE 0 END) `top5`,
SUM(CASE WHEN rating < 4 THEN 5 ELSE 0 END) `top3`
FROM Table1
GROUP BY username
ORDER BY `1st places` DESC
) q, (SELECT @n := 0) n
答案 1 :(得分:0)
我很确定您无法在同一SELECT
查询中重复使用具有计算值的字段,但是可以选择包装到其他子查询中:
SELECT username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`, `top5`, `top3
FROM
(
SELECT
*,
`1st places`+`2nd places`+`3rd places` `total finishes`
FROM (
SELECT username,
SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) `3rd places`,
SUM(CASE WHEN rating < 6 THEN 5 ELSE 0 END) `top5`,
SUM(CASE WHEN rating < 4 THEN 5 ELSE 0 END) `top3`
FROM Table1
GROUP BY username
ORDER BY `1st places` DESC
)
)
q, (SELECT @n := 0) n
还没试过,还是......