从多列中选择DISTINCT

时间:2012-04-26 07:17:52

标签: mysql select distinct

这是一个复杂的查询,但我有一个斯诺克比赛的数据库,我正在尝试生成谁玩过并赢得最多决定帧的统计数据(如果你不这样做,不要担心规则)知道游戏)。

表:

ID player1  player2   bestOf     player1Score      player2Score
1   1           2          9          5                   0
2   2           1          9          5                   4
3   1           2          9          5                   4
4   2           1          9          4                   5

我想做的事情如下:

SELECT COUNT(*) AS played, DISTINCT(player1,player2) AS playerID 
FROM matches 
WHERE (player1Score=BestOf / 2 + 0.5 AND player2Score=BestOf / 2 - 0.5) 
GROUP BY playerID

上述查询不起作用,因为我认为DISTINCT不支持多列。我从顶部表中寻找的结果是:

playerID played  won
1           3      2
2           3      1

不显示表格中的顶行,因为它不是最终帧。

我尝试了以下变体:

SELECT GROUP(player1,player2)
SELECT player1 + player2 AS playerID, select DISTINCT(playerID)
SELECT (player1 + player2) AS playerID GROUP BY playerID

以及其他一些人。任何提示都将不胜感激!

2 个答案:

答案 0 :(得分:0)

我实际上没有你的表,所以我的SQL可能有很多语法错误。但希望我能够全面了解这个概念。 我们可以计算玩家1获胜的决定性框架游戏列表,并将其与玩家2赢得的决定性框架游戏列表结合起来。只要我们将获胜者的列名重命名为相同的字符串('player'),这些表的并集应该产生一个表,标记每个人赢得的次数。

select player, count(*) as num_won from ((select player1 as player from matches where player1Score - player2Score = 1) union (select player2 as player from matches where player2Score - player1Score = 1));

这应该为您提供从每个玩家的ID到他们赢得的次数的映射。

然后考虑

select player, count(*) as num_played from ((select player1 as player from matches where abs(player1Score - player2Score) = 1) union (select player2 as player from matches where abs(player2Score - player1Score) = 1));

使用abs功能可以帮助你发现每个玩家所玩的决定帧游戏的数量。现在我们将这两个表结合起来得到你的最终答案

select players_table.player, players_table.num_played, winners_table.num_won from (select player, count(*) as num_won from ((select player1 as player from matches where player1Score - player2Score = 1) union (select player2 as player from matches where player2Score - player1Score = 1)) winners_table), (select player, count(*) as num_played from ((select player1 as player from matches where abs(player1Score - player2Score) = 1) union (select player2 as player from matches where abs(player2Score - player1Score) = 1)) players_table) where winners_table.player == players_table.player;

答案 1 :(得分:0)

create table temp_score
select playerid, count(*) as won 
FROM(
  Select   case  when player1score > player2score then  player1 else player2 end as playerid
    from score
    where
    (player2Score=Round(BestOf / 2 + 0.5,0) AND player1Score=round(BestOf / 2 - 0.5,0))
    or
    (player1Score=Round(BestOf / 2 + 0.5,0) AND player2Score=round(BestOf / 2 - 0.5,0))
) a
group by playerid

Select playerid,won, (Select SUM(won) from temp_score)  as TotalPlayed  from temp_score