0

我有以下执行基本选择语句的选择 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。它仅用于选择一定范围内的行。

4

1 回答 1

0

您可以通过将行号与原始选择放在评论中来做到这一点。如果你想在像 ROW_NUMBER 这样的窗口函数上有一个 WHERE 子句,你不能去一个。

您确实必须编写TotalFoundUseful + TotalFoundNotUseful两次,但它只会被评估一次,因此不会影响性能。

我也不希望移动到两个会对性能产生任何影响,但您应该对其进行测试。

Select *
    From
    (
  Select *, (TotalFoundUseful + TotalFoundNotUseful) As TotalVotes,
          ROW_NUMBER() OVER
              (ORDER BY
            CASE WHEN @sortBy = 0 THEN DateCreated End Desc,
            CASE WHEN @sortBy = 1 THEN DateCreated end Asc,
            CASE WHEN @sortBy = 2 THEN TotalFoundUseful + TotalFoundNotUseful END Desc,
            CASE WHEN @sortBy = 2 THEN TotalFoundUseful END Desc
          ) AS RowNumber 
 From Reviews
     Where (DealID = @dealID) And (TotalAbuses < 10) And (Deleted = 0)

  ) As Rev
  Where RowNumber BETWEEN @startRecord AND @endRecord
于 2012-05-23T15:00:37.500 回答