2012-08-01 102 views
0

下面的查詢似乎有一個問題來計算「ratingValue」,因爲SUM內有SUM(h.liked)。不能做SUM的SUM嗎?

SELECT d.itemID1 as item, 
    sum(d.sum + d.count*SUM(h.liked))/sum(d.count) as ratingValue 
FROM history h, dev d 
WHERE h.userID=:id_user 
    AND d.itemID1<>h.itemID 
    AND d.itemID2=h.itemID 
GROUP BY d.itemID1,h.itemID 

爲了更好地理解這是當初和工作查詢(從趿拉一種算法):

我剛剛替補的「評級」表「歷史」,因爲在我的情況r.ratingValue是所有的 「喜歡」 一個用戶給出一個ITEMID的(=> r.ratingValue = SELECT SUM(喜歡)從歷史中GROUP BY h.itemID)的總和:

SELECT d.itemID1 as item, 
    sum(d.sum + d.count*r.ratingValue)/sum(d.count) as ratingValue 
FROM rating r, dev d 
WHERE r.userID=$userID 
    AND d.itemID1<>r.itemID 
    AND d.itemID2=r.itemID 
GROUP BY d.itemID1 
+1

你得到了什麼錯誤? – 2012-08-01 02:16:38

+0

我有「組功能無效」 – Anon 2012-08-01 02:32:00

回答

2

由於錯誤消息說,你不能接下來的聚合功能。我想你的意思是:

SELECT d.itemID1 as item, 
     sum(d.sum + d.count*h.sumliked)/sum(d.count) as ratingValue 
FROM (select h.userId, h.itemId, sum(h.liked) as sumliked 
     from history h 
     group by h.userId, h.itemId 
    ) h join 
    dev d 
    on h.userID=:id_user AND 
     d.itemID1<>h.itemID AND 
     d.itemID2=h.itemID 
GROUP BY d.itemID1 

也就是說,您需要分別進行聚合,在這種情況下使用子查詢。我還修復了查詢中的連接語法。

+0

太愉快了,非常感謝。 – Anon 2012-08-01 03:46:14