需要SQL帮助

时间:2010-01-06 09:54:18

标签: 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'附近告诉我语法不正确。

由于

2 个答案:

答案 0 :(得分:3)

(SELECT SUM(Scores.points) FROM Scores WHERE Score.username = Comments.username) AS Points
次选后

PointsPoints列将是SUM()列的名称。

答案 1 :(得分: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