我正在撰写a data explorer query以找到得分最低的答案,这部分工作正常:
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]
相同?{{1}}?或者这根本不可能,我必须手动将其作为存储过程吗?
答案 0 :(得分: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;
答案 1 :(得分:0)
为什么不将upvotes和downvotes视为一张桌子?然后,您可以按照自己的意愿工作。
您可以通过两种方式实现:表值函数或内联表。 选择代码应该是这样的:
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