如何在 SQL PIVOT 中排序

How to ORDER BY in SQL PIVOT(如何在 SQL PIVOT 中排序)
本文介绍了如何在 SQL PIVOT 中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这个查询使用 PIVOT 生成这样的表:

I currently have this query using PIVOT generating a table like this:

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

我想做但看起来有点牵强的是,ORDER BYDEC 值降序排列结果.

What I would like to do but it looks like a stretch is to ORDER BY the results by the DEC value descending.

这是查询:

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 会报错,所以可以指定列吗?

Doing piv ORDER BY piv.Searches gives an error so is it possible to specify the column?

推荐答案

试试这个:

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

这篇关于如何在 SQL PIVOT 中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)