0

我正在编写一个数据浏览器查询以找到得分最低的已接受答案,这部分工作正常:

SELECT TOP 25 a.Id as [Post Link],
              a.Score as Score,
              (SELECT COUNT(*)
               FROM Votes
               WHERE PostId = a.Id AND
                     VoteTypeId = 2) AS [Upvotes],
              (SELECT COUNT(*)
               FROM Votes
               WHERE PostId = a.Id AND
                     VoteTypeId = 3) AS [Downvotes]
FROM Posts q INNER JOIN Posts a ON q.AcceptedAnswerId = a.Id
WHERE a.PostTypeId = 2
ORDER BY a.Score ASC

但是,当我试图计算发布答案的人的分数时,我无法让它接受我选择作为参数的[Upvotes]和列,即:[Downvotes]

SELECT TOP 25 a.Id as [Post Link],
              a.Score as Score,
              (SELECT COUNT(*)
               FROM Votes
               WHERE PostId = a.Id AND
                     VoteTypeId = 2) AS [Upvotes],
              (SELECT COUNT(*)
               FROM Votes
               WHERE PostId = a.Id AND
                     VoteTypeId = 3) AS [Downvotes],
              (15 + (([Upvotes] * 10) - ([Downvotes] * 2))) AS [Answerer's Reputation]
FROM Posts q INNER JOIN Posts a ON q.AcceptedAnswerId = a.Id
WHERE a.PostTypeId = 2
ORDER BY a.Score ASC

我被告知[Upvotes]并且[Downvotes]不是有效的列名:

列名“Upvotes”无效。列名“Downvotes”无效。

我如何表明这[Upvotes]与我刚刚声明的值相同:AS [Upvotes]?或者这根本不可能,我必须作为存储过程手动完成?

4

2 回答 2

1

问题是计算列与引用列的同时计算,因此 SQL 不知道它们。

这将是一种解决方案

SELECT A.[Post Link], 
   A.Score, 
   A.Upvotes, 
   A.Downvotes, 
   (15 + (([Upvotes] * 10) - ([Downvotes] * 2)))AS [Answerer's Reputation]
FROM(SELECT TOP 25 P.Id AS [Post Link], 
                 P.Score AS Score, 
                 (
   SELECT COUNT(*)
     FROM Votes
    WHERE Postid = P.Id
      AND Votetypeid = 2)AS [Upvotes], 
                 (
   SELECT COUNT(*)
     FROM Votes
    WHERE Postid = P.Id
      AND Votetypeid = 3)AS [Downvotes]
     FROM Posts Q
          INNER JOIN Posts P ON Q.Acceptedanswerid = P.Id
    WHERE P.Posttypeid = 2)A
 ORDER BY A.Score ASC;
于 2014-07-15T17:10:05.357 回答
0

您为什么不将赞成票和反对票视为一张桌子?然后,您可以随心所欲地工作。

您可以通过 2 种方式做到这一点:表值函数或内联表。选择你的代码应该是这样的:

SELECT TOP 25 a.Id as [Post Link],
          a.Score as Score,
          [Upvotes].CountVotes as Upvotes,
          [Downvotes].CountVotes as DOwnvotes,
          (15 + (([Upvotes].CountVotes * 10) - ([Downvotes].CountVotes * 2))) AS    [Answerer's Reputation]
  FROM Posts q INNER JOIN Posts a ON q.AcceptedAnswerId = a.Id, 
    (SELECT COUNT(*) as CountVotes
           FROM Votes
           WHERE PostId = a.Id AND
                 VoteTypeId = 2) AS [Upvotes],

          (SELECT COUNT(*) as CountVotes
           FROM Votes
           WHERE PostId = a.Id AND
                 VoteTypeId = 3) AS [Downvotes]
WHERE a.PostTypeId = 2
ORDER BY a.Score ASC
于 2014-07-15T17:25:21.713 回答