MYSQL将两个结果行 - (丢失和获胜团队)合并为一列

时间:2017-06-14 00:00:59

标签: mysql union

我有四列,我想合并如下,按年份分组,game_dt

  GAME_DT     YEAR    WIN    LOSS
  -------------------------------
  20040804    2004    NYN   MIL
  20040804    2004    MIN   ANA
  20040804    2004    NYA   OAK

输出

  GAME_DT     YEAR  TEAM   RESULT
  --------------------------------
  20040804    2004    NYN   W
  20040804    2004    MIL   L
  20040804    2004    MIN   W
  20040804    2004    ANA   L
  20040804    2004    NYA   W
  20040804    2004    OAK   L

更新 我的代码依次是Nitin:

 **

    SELECT 
    GAME_DT,GAME_ID,
    YEAR_ID, 
    if(home_score_ct>away_score_ct,home_team_id,away_team_id) as Team, 
    'W' as result
FROM 
    games 
UNION 
SELECT 
    GAME_DT,game_id,
    YEAR_id, 
    if(home_score_ct<away_score_ct,home_team_id,away_team_id) as Team, 
    'L' as result
FROM 
    games
     group by year_id,game_dt,game_id,result
     order by game_dt,game_id

这很有效!谢谢Nitin让我朝着正确的方向前进。

2 个答案:

答案 0 :(得分:0)

请写下查询sql,以便找到问题

答案 1 :(得分:0)

您可以使用UNION获得结果。

SELECT 
    GAME_DT, 
    YEARS, 
    WIN, 
    'W' 
FROM 
    game_dt 
UNION 
SELECT 
    GAME_DT, 
    YEARS, 
    LOSS, 
    'L' 
FROM 
    game_dt