我有一个名为
的表订阅(user_name varchar(50),video_name varchar(50),watched_date date)
ravi simsons 2016-01-01
ravi dailyshow 2016-02-15
nitin dailyshow 2016-02-24
nitin simsons 2016-02-25
sam simsons 2016-03-04
sam dailyshow 2016-03-04
mat simsons 2016-04-06
cranw simsons 2016-04-15
cranw dailyshow 2016-04-17
simsons和dailyshow是视频的名称
我需要找到在每日播放前观看过Simsons的user_names的独特数量。
我正在努力处理自联接和case语句,但仍无法获得正确的查询。
请帮助!!!
答案 0 :(得分:1)
可以使用每个video_name的单独内联视图并在user_name上加入它们来完成此操作。然后对watched_date条件使用where
子句。
select count(distinct sdaily.user_name)
from (select * from subscriptions where video_name = 'simsons') ssim
join (select * from subscriptions where video_name = 'dailyshow') sdaily
on sdaily.user_name = ssim.user_name
where ssim.watched_date < sdaily.watched_date
答案 1 :(得分:1)
我认为使用聚合最容易:
select count(*)
from (select s.user_name,
min(case when s.video_name = 'simsons' then s.watched_date end) as s_date,
max(case when s.video_name = 'dailyshow' then s.watched_date end) as ds_date
from subscriptions
group by s.user_name
) u
where s_date < ds_date;