2014-02-18 38 views
0

以下SQL代碼是更大的SQL語句的示例。我的問題是我怎麼能CASE多列ORDER BYSELECT ROW_NUMBER(),類似於下面的評論行。呈現的代碼有效,但我需要按兩列排序。OVER子句。如何通過CASE子句中的多個列進行排序?

我使用MSSQL 2008

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 
+0

你有想要的結果的例子嗎? – Kermit

+0

我會嘗試製作和更新問題。 – Dimt

+0

查詢中是否有「GROUP BY」? –

回答

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; 
+0

是的,那可行!謝謝。 – Dimt