2

数据库表包含目标动作。

 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

但我需要它在一条线上显示球员的进球和助攻。干杯。

4

2 回答 2

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与您的查询相关...

于 2012-04-07T13:52:34.170 回答
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 聚合的形式实现的。

于 2012-04-07T16:57:35.203 回答