出于某种原因,这似乎很容易,但我无法弄清楚。所以我有一个名为“contest_entries”的表,其中有“username”和“rating”列。
表格如下所示:
Username | rating | Contest_id
John | 3 | 4
Mike | 1 | 4
Eric | 3 | 5
Mike | 1 | 6
John | 2 | 7
Mike | 1 | 8
John | 1 | 9
因此,对于不同的比赛,人们可以置于不同的位置,
我的问题是如何显示用户名赢得了多少次比赛,获得了第二名或第三名(获得第一名,又名为= 1,第二名被评为= 2,第三名被评为= 3)并列出所有即使用户名从未使用过第1,第2,第3,用户名也是如此。然后最终根据谁获胜最多(谁拥有最多“评级= 1”)对他们进行排名。
所以它看起来像这样:
Username | Ranking | 1st places | Second Places | Third Places
Mike | 1 | 3 | 0 | 0
John | 2 | 1 | 1 | 1
Eric | 3 | 0 | 0 | 1
etc etc.
答案 0 :(得分:1)
SELECT x.username
, COUNT(CASE WHEN rating = 1 THEN 'foo' END) first
, COUNT(CASE WHEN rating = 2 THEN 'foo' END) second
, COUNT(CASE WHEN rating = 3 THEN 'foo' END) third
FROM ratings x
GROUP
BY username;
答案 1 :(得分:0)
尝试
SELECT username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`
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`
FROM Table1
GROUP BY username
ORDER BY `1st places` DESC
) q, (SELECT @n := 0) n
输出:
| USERNAME | RANKING | 1ST PLACES | 2ND PLACES | 3RD PLACES | ------------------------------------------------------------- | Mike | 1 | 3 | 0 | 0 | | John | 2 | 1 | 1 | 1 | | Eric | 3 | 0 | 0 | 1 |
这是 SQLFiddle 演示