2012-04-07 169 views
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 

,但我需要它來顯示球員的進球和助攻在一行。乾杯。

+1

你能顯示導致這個結果的查詢嗎? – 2012-04-07 13:55:00

+1

爲什麼不把你在另一個查詢中使用'select player,sum(goals),sum(assist)from()group by player'查詢的東西?儘管如此,你仍然需要顯示你的原始查詢......「按玩家分組」應該是你原來需要的所有東西 – vol7ron 2012-04-07 14:09:32

回答

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

一個可能的解決辦法是用旋轉第一unpivot的球員的名字,然後組:

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 

Unpivoting我這是通過使用交叉連接到虛擬表完成的,分組/旋轉是以與CASE聚合的形式實現的。