Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Manipulating non-normalized table data 2

Status
Not open for further replies.

NuJoizey

MIS
Aug 16, 2006
450
US
Say I have data in tblMovie like so:

Code:
MovieTitle               Genre       Director
--------------------     ------      --------
Sleepless In Seattle     Comedy      Jones
Sleepless In Seattle     Romance     Jones
Die Hard2                Action      Smith
When Harry Met Sally     Romance     Jones

If I execute:

SELECT MovieTitle FROM tblMovie WHERE Director = "Jones", I would get:
Code:
MovieTitle               Genre       Director
--------------------     ------      --------
Sleepless In Seattle     Comedy      Jones
Sleepless In Seattle     Romance     Jones
When Harry Met Sally     Romance     Jones

The result set would return 3 titles - but that's not really accurate, because it really should only be two titles.


Without using a reporting tool, in TSQL is there a way to return a result set that looks something like:

Code:
MovieTitle               Genre               Director
--------------------     ------              --------
Sleepless In Seattle     Comedy/Romance      Jones
When Harry Met Sally     Romance             Jones
 
Hi,

If you're using SQL2005, you can use xml path and do it in one query...

Code:
declare @tblmovie table (movie varchar(20), genre varchar(20), director varchar(20))
insert into @tblmovie values('Sleep', 'Comedy', 'Jones')
insert into @tblmovie values('Sleep', 'Romance', 'Jones')
insert into @tblmovie values('Die', 'Action', 'Smith')
insert into @tblmovie values('Harry', 'Romance', 'Jones')

select t1.movie, t2.genre, t1.director
from @tblmovie t1
join (
 select movie,
 replace((
     select genre as 'data()'
     from @tblmovie t2 
     where t1.movie = t2.movie
     for xml path('')),' ',',') as genre
 from @tblmovie t1
 group by movie) as t2 on t1.movie = t2.movie
where director = 'Jones'
group by t1.movie, t1.director, t2.genre

Ryan
 
Ryan,

very tidy - you should supplement the faqs and add this in with a brief explanation, but definitely worth a star.

Cheers

"I'm living so far beyond my income that we may almost be said to be living apart
 
actually, i happen to be using oracle for this one, and since i frequent this board I forgot that it was specific to MSSQL. So I should probably repost there, as there is probably a corresponding pl sql way to do it. But these examples are helpful nonetheless, and I do thank you all for your posts.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top