2013-03-11 27 views
1

我有一個餐館評分和評論數據庫,每個餐廳可以有1到大約1000條評論。同時檢索'count where'和和總數

我第一次嘗試找出哪些餐館有最4+額定條評論註釋包括「塔科」這個詞,我得到了它與下面的代碼工作:

select id, count(id) from test where (comment like '%taco%') AND rating >= 3 group by id order by count(id) DESC; 

因此,舉例來說,如果餐廳X有三十個4+評級,包括'塔科',我會得到'X | 30'的線。

我想補充兩個額外的特性:

  1. 列表評論總數爲每個餐廳(不附加任何條件)
  2. 給出的平均得分爲所有的餐廳的評論,其中包括「塔科」 。

如果餐館X擁有150分總的評價,其中30是4+場所,包括「塔科」,平均得分爲那些30條是2.5,我會得到:

「X | 30 | 150 | 2.5 |」

我該如何得到這個結果?

+0

4 +評論評論的平均值如何爲2.5? – 2013-03-11 19:51:08

+0

不應該4+收視率爲「收視率= 4」嗎? – user1766760 2013-03-11 19:54:23

+0

很好,呃。我的意思是包括'taco'在內的所有餐廳評論的平均評分是2.5。所以有30個4+以上的評論和很多較低的評論。 – user1956609 2013-03-11 19:54:29

回答

6

這樣的事情可能會奏效。

select id 
, count(*) totalreviews 
, sum(case when rating >= 3 and comment like '%taco%' then 1 else 0 end) ratings4plus 
, avg(case when rating >= 3 and comment like '%taco%' then rating else null end) avgratings4plus 
from test 
group by id 
+0

非常完美,非常感謝! – user1956609 2013-03-11 20:04:36

1

使用子查詢:

SELECT id, 
     (SELECT COUNT(*) 
     FROM test 
     WHERE id = t1.id 
      AND comment LIKE '%taco%' 
      AND rating >= 3), 
     (SELECT COUNT(*) 
     FROM test 
     WHERE id = t1.id), 
     (SELECT AVG(rating) 
     FROM test 
     WHERE id = t1.id 
      AND comment LIKE '%taco%' 
      AND rating >= 3), 
FROM (SELECT DISTINCT id 
     FROM test) AS t1 
2

這是未經測試,但你可能嘗試像

select id, 
     count(id), 
     sum(case when (comment like '%taco%' and rating >=3) then 1 
       else 0 end) taco_rating, 
     avg(case when comment like '%taco%' then rating else null end) avg_taco 
    from test 
group by id 
1

4+,您的測試應該是rating > 3而非rating >= 3,但是這將做到這一點:

select 
    id, 
    sum(case when comment like '%taco%' 
      AND rating > 3 then 1 else 0 end) as rating4plus_count, 
    count(*) as all_ratings_count, 
    avg(case when comment like '%taco%' 
      AND rating > 3 then rating else null end) as rating4plus_avg 
from test 
group by id 
order by 1 DESC; 

注簡寫爲order by 1,它是按「列編號1」排序的SQL標準方式(而不是重複列1中的表達式order by clause)