简体   繁体   English

使用行号对数据进行分区

[英]Using Row Number to Partition data

Okay this is one of those situations where I have concluded that I am lost. 好的,这是我断定我迷路的情况之一。

I have a table that looks like this: 我有一个看起来像这样的表:

在此处输入图片说明

I have written the following code: 我写了以下代码:

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

I get this result: 我得到这个结果:

在此处输入图片说明

What I don't understand is why am I getting Nulls in the query result? 我不明白的是为什么查询结果中会出现Nulls?

What am I doing wrong? 我究竟做错了什么? As you can see I am categorizing the movies. 如您所见,我正在对电影进行分类。

Thanks for checking this out 感谢您签出

Maybe this approach will work for you. 也许这种方法对您有用。 In general when you're turning row values into columns (like movie types in your example), it's a pivot function (ref http://msdn.microsoft.com/en-us/library/ms177410.aspx ) 通常,当您将行值转换为列时(如示例中的影片类型),它是一个枢轴函数(请参阅http://msdn.microsoft.com/zh-cn/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

Result: 结果:

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

please note that if you are trying to get this type of output the you have to use group by clause .. 请注意,如果您尝试获取此类输出,则必须使用group by子句..

say if you want to get value for all the category then you can try following query .. 如果您想获取所有类别的价值,则可以尝试以下查询..

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 

I think this is what you are trying to do .. 我想这就是你想要做的..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM