如何在SQL PIVOT中进行ORDER BY

时间:2012-12-07 00:19:38

标签: sql sql-server tsql pivot

我目前使用PIVOT生成此查询,生成如下表:

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

我希望做什么,但看起来像是ORDER BY DEC 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

执行{{1}}会出错,是否可以指定列?

1 个答案:

答案 0 :(得分:5)

试试这个:

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