5

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

3 回答 3

2

重复表达式是一种方法,就像将它放在子查询或 CTE 中一样,例如:

;WITH cte AS
(
  SELECT
   a.PostID
  ,a.Title
  ,a.Date_Created 
  ,(SELECT COUNT(VoteID)  
     FROM VoteTable WHERE PostID = a.PostID) AS VoteCount
   FROM dbo.PostTable AS a
   INNER JOIN dbo.Users AS b
   ON a.Created_UserID = b.UserID
   WHERE a.Approved = 1
)
SELECT PostID, Title, Date_Created, VoteCount
FROM cte
ORDER BY 
  CASE @SortBy
    WHEN 1 THEN Date_Created END DESC,
  CASE @SortBy
    WHEN 2 THEN VoteCount END DESC;

但是不是重复表达式,如果你真的为二阶 by 执行条件似乎并不重要。那么为什么不简单地将您现有的更改ORDER BY为:

ORDER BY CASE WHEN @SortBy = 1 THEN a.Date_Created END DESC,
         VoteCount DESC;

在这种情况下,如果@SortBy是 2,则第一个表达式是NULL,因此仍然可以实现您想要的排序。当@SortBy为 1 时,它按日期降序排序,除非有很多关系,Date_Created并且在这种情况下你不想看到这些关系按 排序VoteCount DESC,次要顺序是无关紧要的,所以你不需要换行它在第二个CASE表达式中。

顺便说一句,原因是当您将CASE表达式引入 时ORDER BY,您会更改 SQL Server 解析/评估查询的方式,并且您不能再从SELECT列表中引用别名。这就是为什么CASEORDER BY子句中删除不再抱怨列名无效的原因。

于 2013-08-06T23:55:16.123 回答
1

代替:

WHEN 2 THEN [VoteCount] END DESC

和:

WHEN 2 THEN (SELECT COUNT(VoteID) AS VoteCount 
 FROM [VoteTable] WHERE [PostID] = a.[PostID]) END DESC
于 2013-08-06T22:56:19.223 回答
0
SELECT
 a.[PostID]
,a.[Title]
,a.[Date_Created] 
,V.VoteCount 
FROM [PostTable] a
INNER JOIN (SELECT PostID, COUNT(VoteID) AS VoteCount GROUP BY PostID) V
     ON V.[PostID] = a.[PostID]
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 V.[VoteCount] END DESC
于 2013-08-07T00:47:33.083 回答