简体   繁体   中英

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?

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 )

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 ..

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 ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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