我在MSSQL中有两个表;
视频: ID, 艺术家, 标题
runlog: 视频ID, 日期时间
我试图整理的结果显示:
ID, 艺术家, 标题, 在过去1小时内播放的时间ID, 在过去12小时内播放的时间ID, 过去24小时内播放的时间ID, 时代艺术家
我找到了除最后一栏之外的所有内容。
SELECT ID,Artist,Title,
(select COUNT(*) from runlog where runlog.videoID = videos.id ) as plays,
(select COUNT(*) from runlog where datetime > DATEADD(hh,-1,GETDATE()) and runlog.videoID = videos.id) as hr1plays ,
(select COUNT(*) from runlog where datetime > DATEADD(hh,-12,GETDATE()) and runlog.videoID = videos.id) as hr12plays ,
(select COUNT(*) from runlog where datetime > DATEADD(hh,-24,GETDATE()) and runlog.videoID = videos.id) as day1plays ,
(select COUNT(*) from runlog left join videos on videos.ID = runlog.videoID
where videos.artist = Artist and runlog.videoID = videos.id) as artistplays
FROM videos
显然,最后一件事只是显示了runlog表中的记录总数,但是我想把它放在我想要做的事情上。
我首先尝试寻找解决方案,但我找不到任何可以帮助的方法。
谢谢!
答案 0 :(得分:0)
我认为你可以通过聚合和窗口函数来实现这一点,结合起来:
SELECT v.ID, v.Artist, v.Title,
count(rl.videoid) as plays,
sum(case when datetime > DATEADD(hh, -1 ,GETDATE()) then 1 else 0
end) as hr1plays,
sum(case when datetime > DATEADD(hh, -12, GETDATE()) then 1 else 0
end) as hr12plays,
sum(case when datetime > DATEADD(hh, -24, GETDATE()) then 1 else 0
end) as hr24plays,
sum(count(rl.videoid)) over (partition by v.Artist) as artistplays
FROM videos v left outer join
runlog rl
on v.id = rl.videoId
group by v.ID, v.Artist, v.Title;