2013-07-31 52 views
0

我已經繼承了以下查詢,該查詢獲得指定「嘗試」(橄欖球術語觸地得分)的平均評分。希望我們仍然可以使用它。評分查詢 - 指定ID超過全部評分的評分的評分百分比

SELECT i.id, i.title, 
     (
      CASE 
       WHEN 
        COUNT(r.rating) > 0 
       THEN 
        (
         SUM(r.rating)/COUNT(r.rating) 
        ) 
       ELSE 
        0 
      END 
     ) AS rating, 

     COALESCE(er.id, 0) AS has_existing_rating 
    FROM 
     (
      SELECT 1 AS id, 'Try 1 – Israel Dagg v Chiefs.' as title UNION ALL 
      SELECT 2 AS id, 'Try 2 – Israel Dagg v Chiefs.' as title UNION ALL 
      SELECT 3 AS id, 'Try 3 – Leilia Masaga v Crusaders.' as title UNION ALL 
      SELECT 4 AS id, 'Try 4 – Israel Dagg v Chiefs.' as title UNION ALL 
      SELECT 5 AS id, 'Try 5 – Fred Flintstone v Hurricanes.' as title UNION ALL 
      SELECT 6 AS id, 'Try 6 – Israel Dagg v Chiefs.' as title UNION ALL 
      SELECT 7 AS id, 'Try 7 – Israel Dagg v Chiefs.' as title 
     ) AS i 

    LEFT OUTER JOIN 
     tryPoll r 
    ON 
     i.id = r.try_id 

    <!-- 
     Join this to the rating table AGAIN to see if the current 
     user has already rated the given try. 
    --> 
    LEFT OUTER JOIN 
     tryPoll er 
    ON 
     (
       er.try_id = i.id 
      AND 
       er.ip_address = '#cgi.remote_addr#' 
      AND 
       er.user_agent = '#cgi.http_user_agent#' 
     ) 

    GROUP BY 
     i.id, 
     r.try_id, 
     er.id, 
     i.title 
    ORDER BY 
     i.id ASC 

因此,如下表(等級= 1只意味着一票在這種情況下)....

tryPoll

id  try_id  rating  ip_address  user_agent 
    ------------------------------------------------------ 
    1  2   1   58.28.220.51 Mozilla/5.0 blah 
    2  2   1   58.28.220.52 Mozilla/5.0 blah 
    3  6   1   58.28.220.53 Mozilla/5.0 blah 
    4  4   1   58.28.220.54 Mozilla/5.0 blah 

...查詢將返回try_id#2的平均評分爲(1 + 1)/ 2 = 1

但是,我需要調整此查詢以返回特定TRY的評分百分比,而不是所有嘗試的評分。即在上面的例子中,確定所有嘗試的所有評級的百分比歸因於try_id#2

我該如何實現?

+1

,如果有更多的樣本數據(即如果'rating'是爲了能夠有不同的值,請出示一些),並預期這將有助於結果。 –

回答

1

你可以試試這個解決方案:

DECLARE @try_id INT; 
SET @try_id=2; 

SELECT r.try_id, 
     SUM(r.rating) AS ratings_per_try, 
     SUM(SUM(r.rating)) OVER() AS ratings_overall, 
     SUM(r.rating)*1.0/NULLIF(SUM(SUM(r.rating)) OVER(), 0) AS percent_try  
FROM Table r 
GROUP BY r.try_id 
+0

美麗!非常感謝! – user460114