以下SQL代码是较大SQL语句的示例。我的问题是如何在CASE
中ORDER 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}}
答案 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;