我有以下执行基本选择语句的选择 SQL,尽管它确实包含计算列:
Select *
From
(
Select *,
ROW_NUMBER() OVER
(ORDER BY
CASE WHEN @sortBy = 0 THEN R.DateCreated End Desc,
CASE WHEN @sortBy = 1 THEN R.DateCreated end Asc,
CASE WHEN @sortBy = 2 THEN TotalVotes END Desc,
CASE WHEN @sortBy = 2 THEN R.TotalFoundNotUseful END Desc
) AS RowNumber
From
(
Select *, (TotalFoundUseful + TotalFoundNotUseful) As TotalVotes
From Reviews
Where (DealID = @dealID) And (TotalAbuses < 10) And (Deleted = 0)
) As R
) As Rev
Where RowNumber BETWEEN @startRecord AND @endRecord
如果仔细看,SELECT 语句本身执行了 3 次。我不敢相信这是必要的。有没有办法将其减少到 2 个选择语句(甚至可能是一个)。我实际上不需要返回 RowNumber。它仅用于选择一定范围内的行。