2010-01-06 26 views
0

幫助我有以下查詢,似乎做什麼我也想,但我認爲有可能是一個更短的方式需要使用SQL

CREATE TABLE #userScoreForComment (
     comment_id int, 
     points int 
    ) 

    INSERT INTO #userScoreForComment 
    SELECT comment_id, SUM(Scores.points) AS Points 
    FROM Comments INNER JOIN Scores ON Comments.username = Scores.username 
    WHERE Comments.upload_id = @uploadid 
    GROUP BY comment_id 

    SELECT Comments.comment_id, username, comment_text, post_date, Points 
    FROM Comments JOIN #userScoreForComment on Comments.comment_id = #userScoreForComment.comment_id 
    WHERE upload_id = @uploadid 

我在做這個較短的嘗試已經失敗,這就是我有

SELECT Comments.comment_id, username, comment_text, post_date, 
     Points AS (SELECT SUM(Scores.points) FROM Scores WHERE Score.username = Comments.username) 
    FROM Comments 
    WHERE Comments.upload_id = @uploadid 
    GROUP BY Comments.comment_id 

SQL服務器告訴我關鍵字'FROM'附近的語法不正確。

感謝

+0

我認爲不正確的語法是因爲內部的select語句[點爲(選擇...]沒有在'from'子句中指定註釋,但是在'where'子句中使用了它,雖然沒有嘗試過。 – shunty

回答

3
(SELECT SUM(Scores.points) FROM Scores WHERE Score.username = Comments.username) AS Points 

Points子查詢後! Points將是該名稱的SUM()列。

0

這有點整潔使用連接,而不是一個嵌套的SELECT,計算SUM:

SELECT Comments.comment_id, Comments.username, comment_text, post_date, SUM(Scores.points) 
FROM Comments INNER JOIN Scores ON Comments.username = Scores.username 
WHERE upload_id = @uploadid 
GROUP BY comment_id, Comments.username, comment_text, post_date