小编典典

SQL Server-通过子查询按名称排序

sql

在下面,我的第二种情况不起作用,因为我从子查询中引用了该名称。对这个问题有什么好的解决方案?另外,我声明了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

阅读 249

收藏
2021-05-23

共1个答案

小编典典

代替:

WHEN 2 THEN [VoteCount] END DESC

和:

WHEN 2 THEN (SELECT COUNT(VoteID) AS VoteCount 
 FROM [VoteTable] WHERE [PostID] = a.[PostID]) END DESC
2021-05-23