试图找出两个avg给出错误之间的区别?
http://sqlfiddle.com/#!3/7160d/9
select * from
(
select avg(avg_stars) as avg_1
from
(
select r.mid, avg(stars) as avg_stars
from
rating r inner join movie m
on r.mid = m.mid
where year < '1980'
group by r.mid
)
)
-
(
select avg(avg_stars) as avg_2
from
(
select r.mid, avg(stars) as avg_stars
from
rating r inner join movie m
on r.mid = m.mid
where year > '1980'
group by r.mid
)
)
答案 0 :(得分:2)
应该是“一点点”简化
select
avg(case when year < '1980' then stars end) -
avg(case when year > '1980' then stars end)
from movie m
inner join
(select mId, Cast(stars as int) as stars from Rating) r
on m.mID = r.mID
或(如果星号类型正确,则删除演员表)
select
avg(case when year < '1980' then cast (stars as int) end) -
avg(case when year > '1980' then cast(stars as int) end)
from movie m
inner join
Rating r
on m.mID = r.mID
请参阅SqlFiddle
答案 1 :(得分:1)
这是你想要的。
select
(
select avg(avg_stars) as avg_1
from
(
select r.mid, avg(convert(int,stars)) as avg_stars
from
rating r inner join movie m
on r.mid = m.mid
where year < '1980'
group by r.mid
) x
)
-
(
select avg(avg_stars) as avg_2
from
(
select r.mid, avg(convert(int,stars)) as avg_stars
from
rating r inner join movie m
on r.mid = m.mid
where year > '1980'
group by r.mid
) x
)
答案 2 :(得分:0)
另一种方法:
select [stats].Period, avg([stats].stars) as avg_stars
from
(
select
stars,
(case when year > '1980' then 'after 1980' else 'before 1980' end) as [Period]
from rating r inner join movie m on r.mid = m.mid
) [stats]
group by [stats].Period
(如果您date
为year
,则可以将句点设为date