0

たとえば、次のような 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 ステートメントで作成した「1 位」+「2 位」+「3 位」という列を合計し、「合計終了」という別の列を作成するにはどうすればよいですか? 簡単に思えますが、私はそれを理解できないようです。

4

2 に答える 2

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
于 2013-07-01T20:11:07.493 に答える
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

まだ試していません...

于 2013-07-01T20:10:57.120 に答える