2012-12-07 62 views
2

我使用PIVOT產生這樣的表目前有這個疑問:如何ORDER BY在SQL PIVOT

USER | DEC | NOV | OCT 
--------------------------------- 
    bob | 3 | 5 | 2 
    jon | 7 | 0 | 1 
    tim | 4 | 2 | 6 

我想這樣做,但它由DEC看起來像一個舒展是ORDER BY結果價值下降。

這是查詢:

with Mth (st, nd) as ( 
    select DATEADD (M, datediff (m, 0,'2012-09-01'), 0), 
     DATEADD (M, DATEDIFF (m, 0, '2012-09-01') + 1, 0) 
    union all 
    select DATEADD (m, 1, st), 
     DATEADD (m, 1, nd) 
    from Mth 
    where nd <= DATEADD (m, datediff (m, 0, getdate()), 0) 
) 
select * 
from 
( 
    select MONTH(Mth.st) Month, 
     U.USER, 
     COUNT(S.QRY_ID) Searches 
    FROM Mth 
    LEFT JOIN SEARCHES S 
    on Mth.st <= S.CREATED 
    and Mth.nd > S.CREATED 
    LEFT JOIN MEMBERS U 
    on U.AID = S.AID 
    GROUP BY YEAR(Mth.st), MONTH(Mth.st), U.HOLDER_LOGIN 
) src 
pivot 
( 
    sum(searches) 
    for month in ([12],[11],[10]) 
) piv 

piv ORDER BY piv.Searches給出了一個錯誤所以是有可能指定列?

回答

2

試試這個:

with Mth (st, nd) as ( 
    select DATEADD (M, datediff (m, 0,'2012-09-01'), 0), 
     DATEADD (M, DATEDIFF (m, 0, '2012-09-01') + 1, 0) 
    union all 
    select DATEADD (m, 1, st), 
     DATEADD (m, 1, nd) 
    from Mth 
    where nd <= DATEADD (m, datediff (m, 0, getdate()), 0) 
), Pivoted 
AS 
(  
    select * 
    from 
    ( 
     select MONTH(Mth.st) Month, 
      U.USER, 
      COUNT(S.QRY_ID) Searches 
     FROM Mth 
     LEFT JOIN SEARCHES S 
     on Mth.st <= S.CREATED 
     and Mth.nd > S.CREATED 
     LEFT JOIN MEMBERS U 
     on U.AID = S.AID 
     GROUP BY YEAR(Mth.st), MONTH(Mth.st), U.HOLDER_LOGIN 
    ) src 
    pivot 
    ( 
     sum(searches) 
     for month in ([12],[11],[10]) 
    ) piv 
) 
SELECT * 
FROM Pivoted 
ORDER BY Dec 
+0

謝謝,但什麼是'Dsc'? – greener

+0

@greener - 對不起,它是'DEC',或者其他你想要訂購的專欄。 –

+0

啊是的!在我的例子中,'ORDER BY [12]'。非常感謝 – greener