2014-01-14 33 views
0

試圖找出兩個平均給出錯誤之間的區別?SQL查詢平均差異顯示錯誤?

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 
) 
) 
+3

爲什麼'stars'聲明爲'varchar'時,它應該(顯然)只包含數值數據? –

+0

@Damien_The_Unbeliever感謝數據類型不匹配。 –

回答

2

應該是 「littlbe位」 簡化

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

這是你想要的。

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 
) 
+0

不是int它應該是十進制的。 –

+0

好吧按照..... – Kishore

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的情況下,你有yeardate

http://sqlfiddle.com/#!3/2bf4e/26