在下面,我的第二种情况不起作用,因为我从子查询中引用了该名称。对这个问题有什么好的解决方案?另外,我声明了SortBy参数...只是在示例中未包括该参数。非常感谢您的帮助!

SELECT
 a.[PostID]
,a.[Title]
,a.[Date_Created]
,(SELECT COUNT(VoteID) AS VoteCount
     FROM [VoteTable] WHERE [PostID] = a.[PostID]) AS VoteCount

FROM [PostTable] a
INNER JOIN [Users] b
ON a.Created_UserID = b.UserID
WHERE a.Approved = 1

ORDER BY
CASE @SortBy
    WHEN 1 THEN a.[Date_Created] END DESC,
CASE @SortBy
    WHEN 2 THEN [VoteCount] END DESC

最佳答案

代替:

WHEN 2 THEN [VoteCount] END DESC

和:
WHEN 2 THEN (SELECT COUNT(VoteID) AS VoteCount
 FROM [VoteTable] WHERE [PostID] = a.[PostID]) END DESC

10-08 03:37