SQL:查询2个表并按另一个表中的值对结果进行排序

时间:2013-11-19 11:09:48

标签: sql sql-server tsql

是否可以为单个记录选择所有评论,并按正面:另一张表中的负投票的整体比率对它们进行排序?

我想我可能需要使用subselect但我真的不确定如何或在哪里。

2张表:

表1 [评论]

ID  |  RecordID  |  Comment  
------------------------------
1   | 100001     | blah blah
2   | 100202     | another co
3   | 100054     | lorem ips

表2 [评级]

ID  | CommentID  |  Vote  
-------------------------
1   | 1          | 1       
2   | 1          | 0
3   | 1          | 1
4   | 3          | 0
5   | 3          | 0
6   | 3          | 0

请注意:'投票':0 =反对票; 1 =正投票 另外,我使用的是Microsoft SQL Server

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

要将它们从正评级排序到负评级,您可以这样做:

SELECT c.id,
  c.recordID,
  c.comment
FROM comments c
INNER JOIN (
  SELECT CommentID,
  SUM(CASE WHEN Vote = 0 THEN -1 ELSE 1 END) AS RATING FROM ratings
  GROUP BY commentID
  ) r ON r.commentID = c.id
ORDER BY r.RATING DESC;

sqlfiddle demo

请注意,我使用CASE给0的值为-1,否则10个负数和1个正值将给出1的等级。

此查询未考虑没有分数的评论。如果你想让没有分数的评论得到0分,你可以这样做:

SELECT c.id,
  c.recordID,
  c.comment
FROM comments c
LEFT JOIN (
  SELECT CommentID,
  SUM(CASE WHEN Vote = 0 THEN -1 ELSE 1 END) AS RATING FROM ratings
  GROUP BY commentID
  ) r ON r.commentID = c.id
ORDER BY COALESCE(r.RATING,0) DESC;

编辑:

要获得比率,请尝试:

SELECT c.id,
  c.recordID,
  c.comment,
  r.rating
FROM comments c
LEFT JOIN (
  SELECT CommentID,
    SUM(CASE 
        WHEN Vote = 1
          THEN 1
        ELSE 0
        END) / (nullif(COUNT(*) * 1.0, 0)) AS RATING
  FROM ratings
  GROUP BY commentID
  ) r ON r.commentID = c.id
ORDER BY COALESCE(r.RATING, 0) DESC;

sqlfiddle demo