我们有两个表历史(历史)和当前(库尔)。请参阅图片了解详情 我必须每天更新基于Curr的Hist,当用户收听给定歌曲时,它会实时记录。基本上,在每天结束时,我们转到Curr并拉出每个用户/歌曲组合的计数,然后将此计数添加到具有生命周期计数的Hist。如果这是用户第一次收听某首歌曲,我们在历史记录中不会有这对,所以我们必须在那里创建该对,然后添加最后一天的计数。
以下是我正在尝试的代码,以及一些问题:
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;
答案 0 :(得分:0)
如果您使用的是Oracle,我认为这样的MERGE INTO
语句应该就是您所需要的。
MERGE INTO history H
USING (SELECT user_id,
song,
Count (*) AS song_cnt
FROM CURRENT C
GROUP BY user_id,
song) c
ON ( c.user_id = h.user_id AND c.song=h.song )
WHEN matched THEN
UPDATE SET h.song_cnt = h.song_cnt + c.song_cnt
WHEN NOT matched THEN
INSERT (todays_date,
user_id,
song,
song_cnt)
VALUES (SYSDATE, -- or your date variable
c.user_id,
c.song,
c.song_cnt) ;