2011-07-19 46 views
2

我試圖獲得由用戶贏得的獎品的唯一數量的報告。即。如何球員贏得了所有3個獎項,有多少人獲得了2個獎項,等等。MySQL需要一個查詢使用GROUP BY column_a也忽略column_b的重複項

+--------+--------+ 
| player | prize | 
+--------+--------+ 
| 1 | 1 | 
+--------+--------+ 
| 1 | 1 | 
+--------+--------+ 
| 1 | 2 | 
+--------+--------+ 
| 1 | 3 | 
+--------+--------+ 
| 2 | 1 | 
+--------+--------+ 
| 2 | 2 | 
+--------+--------+ 

我需要看起來應該是這樣的報告:

+-----------+------------+ 
| prize_qty | player_qty | 
+-----------+------------+ 
|  3 |  1  | 
+-----------+------------+ 
|  2 |  1  | 
+-----------+------------+ 

下面的代碼是接近:

SELECT DISTINCT COUNT(*) as player_qty, prize_qty FROM 
(SELECT count(*) AS prize_qty FROM `prizes` GROUP BY player) 
as t1 GROUP BY player_qty 

,但它返回:

+-----------+------------+ 
| prize_qty | player_qty | 
+-----------+------------+ 
|  4 |  1  | 
+-----------+------------+ 
|  2 |  1  | 
+-----------+------------+ 

我需要它忽略那個玩家#1兩次贏得獎金#1,但我不確定如何進一步消除重複。

回答

3

你說

如何球員贏得了所有3個獎項,有多少人獲得了2個獎項,等等。

我需要它忽略該玩家#1兩次贏得獎品#1

因此,除去玩家多次贏得同一獎金的事實後,您不應該在每個獎勵中計入玩家嗎?

SELECT COUNT(*) AS player_qty, prize AS prize_qty 
FROM 
    (SELECT DISTINCT prize, player FROM prizes) AS T1 
GROUP BY prize 
+0

你正要那裏。最終結果是這個SELECT DISTINCT COUNT(*)作爲player_qty,prize_qty FROM(SELECT count(*)AS prize_qty FROM(SELECT DISTINCT獎,玩家 FROM'prizes')作爲t2 GROUP BY玩家)作爲t1 GROUP BY prize_qty –

0
SELECT DISTINCT COUNT(*) as player_qty, prize_qty FROM 
(SELECT count(*) AS prize_qty FROM `prizes` GROUP BY player, prize) 
as t1 GROUP BY player_qty 
0

試試這個:

SELECT DISTINCT COUNT(player) as player_qty, prize_qty FROM 
(SELECT count(distinct prize) AS prize_qty, player FROM `prizes` GROUP BY player) 
as t1 GROUP BY prize_qty