使用行号来分区数据

时间:2012-04-22 07:17:26

标签: sql sql-server database pivot

好的,这是我得出结论我迷路的情况之一。

我有一个看起来像这样的表:

enter image description here

我写了以下代码:

WITH CTE AS(
SELECT 
 USER_NBR
,CASE WHEN MOVIE_TYPE = 'Action'      THEN MOVIE_NAME END [ACTION]                        
,CASE WHEN MOVIE_TYPE = 'Drama'       THEN MOVIE_NAME END DRAMA
,CASE WHEN MOVIE_TYPE = 'Romance'     THEN MOVIE_NAME END ROMANCE
,ROW_NUMBER() OVER (PARTITION BY  USER_NBR ORDER BY  USER_NBR) AS OCCURANCE
FROM dbo.MOVIE)

SELECT * FROM CTE WHERE OCCURANCE = 1

我得到了这个结果:

enter image description here

我不明白为什么我在查询结果中获得Null?

我做错了什么?正如你所看到的,我正在对电影进行分类。

感谢您查看此内容

2 个答案:

答案 0 :(得分:3)

也许这种方法对你有用。通常,当您将行值转换为列(例如示例中的电影类型)时,它就是一个数据透视功能(参考http://msdn.microsoft.com/en-us/library/ms177410.aspx

select * from 
(select user_nbr, movie_name, movie_type from movies) as movies
pivot 
(max(movie_name)
    for movie_type in ([Action], [Drama], [Romance])
)
as PivotTable

结果:

user_nbr   Action             Drama           Romance
101        Casino Royale    Pretty Woman    Love Actually
102        Casino Royale    Pretty Woman    Love Actually

答案 1 :(得分:0)

请注意,如果您尝试获取此类输出,则必须使用group by子句。

如果您想获得所有类别的价值,那么您可以尝试以下查询..

WITH CTE AS(
SELECT 
 USER_NBR
,CASE WHEN MOVIE_TYPE = 'Action'      THEN MOVIE_NAME END [ACTION]                        
,CASE WHEN MOVIE_TYPE = 'Drama'       THEN MOVIE_NAME END DRAMA
,CASE WHEN MOVIE_TYPE = 'Romance'     THEN MOVIE_NAME END ROMANCE
,count(*) AS OCCURANCE
FROM dbo.MOVIE
 group by USER_NBR
)
SELECT * FROM CTE 

我认为这就是你要做的事情。