Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 get unique records?

Author  Topic 

tech1
Starting Member

49 Posts

Posted - 2011-07-07 : 16:35:53
Hi. I didnt know how to word the subject but hope someone can help.

I have tables:

Tracks
TrackID
TrackName
ArtistID (FK)
GenreID (FK)


Due to the unfortunately design, I am trying to get "rid" of GenreID and put that into a joining table called "GenreTrack":

GenreTrack
ID
TrackID (FK)
GenreID (FK)

1 track can have many genres it can be associated with.

I want to take the data from the Tracks table and only copy the records where:

1) A track has a single genre associated with it (in the tracks table)
2) A track has multiple genres associated with it (multiple records but genreID would be different) but only take 1 of these subset of this record and form a relationship between the first record and many genres its associated with.

does this make sense?

example:

TrackID 1
GenreID 1
TrackName Blah

TrackID 2
GenreID 1
TrackName Help me

TrackID 2
GenreID 2
TrackName Help me

TrackID 2
GenreID 34
TrackName Help me


so the first record would be a satisfied criteria
the second record is a satisfied criteria BUT also has another associated record with it but a different genre. I want to take just one of this record and have all the genres associated for this record and put this into the joining table genreTrack

any ideas?

vaari
Starting Member

15 Posts

Posted - 2011-07-08 : 03:43:29
Assuming that I understood what you said - does this resemble what you are looking for?


DECLARE @Tracks TABLE(TrackID int NOT NULL, TrackName varchar(50) NOT NULL,
GenreID int NOT NULL,ArtistId int NOT NULL);

DECLARE @GenreTracks TABLE(ID int NOT NULL IDENTITY(1,1),TrackId int NOT NULL,
GenreId int NOT NULL);

INSERT @Tracks(TrackID,TrackName,GenreID,ArtistId)
SELECT 100,'Track-100',100,100
UNION ALL
SELECT 200,'Track-200',100,100
UNION ALL
SELECT 300,'Track-300',100,200
UNION ALL
SELECT 400,'Track-400',400,200
UNION ALL
SELECT 500,'Track-500',500,300
UNION ALL
SELECT 100,'Track-100',400,100
UNION ALL
SELECT 100,'Track-100',500,100

INSERT @GenreTracks(GenreId,TrackId)
SELECT DISTINCT GenreID,TrackID FROM @Tracks;

;WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY TrackId,ArtistId ORDER BY ArtistID) RowCtr,
TrackID,
TrackName,
ArtistId,
GenreID
FROM @Tracks
)
-- the data to be retained
SELECT 'FinalList',TrackID,TrackName,ArtistId FROM CTE WHERE RowCtr = 1;
-- run this delete to delete data and retain what is needed
--DELETE CTE WHERE RowCtr > 1
-- drop the GenreId column after deleting the rows

SELECT 'FullList',* FROM @Tracks;
SELECT * FROM @GenreTracks;


If this isn't what you wanted - could you use the sample code above to explain what you need?
Go to Top of Page
   

- Advertisement -