We have two tables History (Hist) and Current (Curr). see pic for details I have to update Hist on a daily basis based on Curr that records in real time when a user listens to a given song. Basically, at the end of each day, we go to Curr and pull a count of each user/song combination and then add this count to Hist that has the lifetime count. If it is the first time a user has listened to a given song, we won't have this pair in Hist, so we have to create the pair there and then add the count of the last day.
Below is the code that I am trying, and a few questions:
- Does it look ok, or am I making an error?
- Do I need to write the query again in the IS NOT NULL condition as I am doing currently
- Is there a better and more efficient way of doing this?
Select case
when IS NULL
(
Select User_ID, Song
From History H,
(Select User_ID, Song, count (*) as song_cnt
From Current C
Group by User_ID, Song) as X
Where X.User_ID = H.User_ID
AND X.Song=H.Song
)
Then
(Update History Set Count = Count +X.Song_cnt, where History.User_ID = User_ID AND History.Song = Song)
When IS NOT NULL
(
Select User_ID, Song
From History H,
(Select User_ID, Song, count (*) as song_cnt
From Current C
Group by User_ID, Song) as X
Where X.User_ID = H.User_ID
AND X.Song=H.Song
)
Then
(Insert into History values (todays_date, User_ID, Song, X.Song_cnt)
End;