Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL PIVOT中按顺序排序_Sql_Sql Server_Tsql_Pivot - Fatal编程技术网

如何在SQL PIVOT中按顺序排序

如何在SQL PIVOT中按顺序排序,sql,sql-server,tsql,pivot,Sql,Sql Server,Tsql,Pivot,我目前使用PIVOT生成如下表: USER | DEC | NOV | OCT --------------------------------- bob | 3 | 5 | 2 jon | 7 | 0 | 1 tim | 4 | 2 | 6 我想做的是,但它看起来像是一个拉伸,是按DEC值降序的结果排序 以下是查询: with Mth (st, nd) as ( select DATE

我目前使用PIVOT生成如下表:

  USER  |  DEC  |  NOV  |  OCT
---------------------------------
  bob   |   3   |   5   |   2
  jon   |   7   |   0   |   1 
  tim   |   4   |   2   |   6
我想做的是,但它看起来像是一个拉伸,是按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进行piv排序。搜索时会出现错误,因此是否可以指定列?

请尝试以下操作:

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或任何其他您想要排序的列。这是对透视操作的输出进行排序的一个极好的解决方案。据我所知,这是不可能的。一两句话来解释你在做什么以及为什么它会起作用是非常有用的。我想出来了,不过说几句话会有帮助的。我必须在两段代码上“找出差异”!真的需要添加一些评论