【问题标题】:How to ORDER BY in SQL PIVOT如何在 SQL PIVOT 中排序
【发布时间】:2012-11-25 03:43:15
【问题描述】:

我目前有这个查询使用 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 会报错,是否可以指定列?

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

    • @greener - 抱歉,它是 DEC,或者您想要订购的任何其他列。
    • 这是对枢轴操作的输出进行排序的出色解决方案。据我了解,否则不可能。
    • 一两句话来解释你在做什么以及它为什么起作用会非常有用。我想通了,但几句话会有所帮助。我必须在两段代码上“找出差异”!
    • 添加一些评论真的很有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2018-12-17
    • 2020-08-24
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多