SQL Server - 多对多查询到1行

时间:2016-07-10 05:57:49

标签: sql sql-server

我有3张桌子

影:

  • Movie_id
  • 标题
  • 运行时
  • Date_id
  • ...

类型:

  • Genre_id
  • 类型

MOVIE_GENRE:

  • Movie_id
  • Genre_id

我想将它们放在一行中,以便每个类型由一列分隔 像这样:

Movie_id | Title | Genre1 | Genre2 | Genre3 | Genre4 |

每部电影最多可包含4种类型。

我接近这种方法:

SELECT
    Movies.Movie_id,
    MAX(Movies.Title),
    MAX(CASE WHEN p.RowNum=1 THEN p.Genre_id END) as Genre1,
    MAX(CASE WHEN p.RowNum=2 THEN p.Genre_id END) as Genre2,
    MAX(CASE WHEN p.RowNum=3 THEN p.Genre_id END) as Genre3,
    MAX(CASE WHEN p.RowNum=4 THEN p.Genre_id END) as Genre4
FROM 
    Movies
JOIN
    (SELECT 
         Movie_Genre.*,
         ROW_NUMBER() OVER (PARTITION BY Movie_id ORDER BY Genre_id) AS RowNum
     FROM 
         Movie_Genre) AS P ON Movies.Movie_id = p.Movie_id
GROUP BY  
    Movies.movie_id      

但我最终得到Genre_id而不是流派名称。

标题栏也未命名为

1 个答案:

答案 0 :(得分:1)

INNER JOIN到子查询中的Genre表

select  Movies.Movie_id,
        Movies.Title,
        MAX(CASE WHEN p.RowNum=1 THEN p.Genre END) as Genre1,
        MAX(CASE WHEN p.RowNum=2 THEN p.Genre END) as Genre2,
        MAX(CASE WHEN p.RowNum=3 THEN p.Genre END) as Genre3,
        MAX(CASE WHEN p.RowNum=4 THEN p.Genre END) as Genre4
FROM    Movies
    INNER JOIN
    (
        SELECT  mg.Movie_id, g.Genre,
                ROW_NUMBER() OVER (PARTITION BY mg.Movie_id ORDER BY mg.Genre_id) 
                as RowNum
        FROM    Movie_Genre mg
                INNER JOIN Genre g  on  mg.Genre_id = g.Genre_id
    ) as P  ON Movies.Movie_id=p.Movie_id
GROUP BY Movies.movie_id, Movies.Title