按两列分组

时间:2012-04-07 13:45:59

标签: mysql sql group-by

数据库表包含目标操作。

 type      goal      assist
 goal      Johnny    James
 goal      Johnny    James
 goal      James     Bob

使用 GROUP BY目标时,协助显示

 player    goals     assists
 Johnny    2         0
 Johnny    0         0
 James     1         0
 James     0         2
 Bob       0         0
 Bob       0         1

但是我需要它来显示球员的进球和助攻。欢呼声。

2 个答案:

答案 0 :(得分:3)

您可以这样做(虽然这可能不是最快的查询,具体取决于您的数据库和索引的大小!):

SELECT players.player,
      -- Use correlated subselects to count goals / assists
      (SELECT COUNT(*) FROM actions WHERE goal = players.player) goals
      (SELECT COUNT(*) FROM actions WHERE assist = players.player) assists

-- Get all distinct players (UNION = DISTINCT, here). Of course, if you
-- have an actual players table, use that one instead!
FROM (
  SELECT goal player FROM actions UNION
  SELECT assist      FROM actions
) players

根据您的问题,我不确定type = goal是否与您的查询相关...

答案 1 :(得分:1)

一种可能的解决方案是首先取消玩家名称的转换,然后使用转动进行分组:

SELECT
  Player,
  COUNT(NULLIF(ScoreType, 'assist')) AS goals,
  COUNT(NULLIF(ScoreType, 'goal')) AS assists
FROM (
  SELECT
    CASE s.ScoreType WHEN 'goal' THEN goal ELSE assist END AS Player,
    s.ScoreType
  FROM GoalActions
  CROSS JOIN (
    SELECT 'goal' AS ScoreType
    UNION ALL SELECT 'assist'
  ) st
) s
GROUP BY
  Player

使用交叉连接到虚拟表进行非透视,并以与CASE聚合的形式实现分组/透视。