OVER条款。如何在CASE子句中按多列排序?

时间:2014-02-18 15:59:15

标签: sql tsql

以下SQL代码是较大SQL语句的示例。我的问题是如何在CASEORDER BY SELECT ROW_NUMBER()多列SELECT TOP(50) ROW_NUMBER() OVER(ORDER BY CASE WHEN @OrderBy = 'Total' THEN SUM(TotalViews) ELSE SUM(LastMonthViews) END DESC) AS Position ,SUM(Albums.TotalViews) AS TotalViews ,SUM(Albums.LastMonthViews) AS LastMonthViews FROM Albums --The code to be implemented in the SELECT ROW_NUMBER() ORDER BY SUM(LastMonthViews) DESC, SUM(TotalViews) DESC ,类似于下面的注释行。提供的代码有效,但我需要按两列排序。

我正在使用MSSQL 2008

{{1}}

1 个答案:

答案 0 :(得分:3)

您可以在case分区子句中重复row_number()语句:

SELECT TOP(50)
        ROW_NUMBER() OVER (ORDER BY (CASE WHEN @OrderBy = 'Total' THEN SUM(LastMonthViews) ELSE SUM(LastMonthViews) END) DESC,
                                    (CASE WHEN @OrderBy = 'Total' THEN SUM(TotalViews) ELSE SUM(LastMonthViews) END) DESC
                          ) AS Position
    ,SUM(Albums.TotalViews) AS TotalViews
    ,SUM(Albums.LastMonthViews) AS LastMonthViews
FROM Albums;