T-SQL:使用ROW_NUMBER简化Select语句

时间:2012-05-23 14:50:38

标签: tsql

我有以下select SQL执行基本的select语句,尽管它包含一个计算列:

    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。它仅用于选择特定范围内的行。

1 个答案:

答案 0 :(得分:0)

你可以通过将rownumber放入原始选择对照评论中来完成。如果你想在像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