0

So say I have a mysql statement like this:

  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

How can I add up the columns that I created called, '1st places' + '2nd places' + '3rd places' in this sql statement and create another column called "total finishes"? Seems easy, but I cannot seem to figure it out.

4

2 回答 2

1

You can just add them together and give an alias to that extra column:-

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
于 2013-07-01T20:11:07.493 回答
0

I'm pretty sure that you can't re-use a field with a calculated value in the same SELECT query, however wrapping into an additional sub-query may be an option:

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

Haven't tried, still...

于 2013-07-01T20:10:57.120 回答