简体   繁体   English

Oracle sql:使用GROUP BY ROLLUP进行排序

[英]Oracle sql: Order by with GROUP BY ROLLUP

I'm looking everywhere for an answer but nothing seems to compare with my problem. 我到处都在寻找答案,但是似乎没有什么可以和我的问题相提并论。 So, using rollup with query: 因此,对查询使用汇总:

select year, month, count (sale_id) from sales 
group by rollup (year, month);

Will give the result like: 将给出如下结果:

  YEAR      MONTH     TOTAL
  2015          1     200
  2015          2     415
  2015       null     615
  2016          1     444
  2016          2     423
  2016       null     867
  null       null    1482

And I would like to sort by total desc, but I would like year with biggest total to be on top (important: with all records that compares to that year), and then other records for other years. 我想按总降序排序,但我希望将拥有最高总年数的年份放在首位(重要:与该年比较的所有记录),然后再列出其他年份的其他记录。 So I would like it to look like: 所以我希望它看起来像:

  YEAR      MONTH     TOTAL
  null       null    1482
  2016       null     867
  2016          1     444
  2016          2     423
  2015       null     615
  2015          2     415
  2015          1     200

Or something like that. 或类似的东西。 Main purpose is to not "split" records comparing to one year while sorting it with total. 主要目的是在与总数进行排序时,不要“拆分”与一年相比的记录。 Can somebody help me with that? 有人可以帮我吗?

Hmmm. 嗯。 I think this does what you want: 我认为这可以满足您的需求:

select year, month, count(sale_id) as cnt
from sales 
group by rollup (year, month)
order by sum(count(sale_id)) over (partition by year) desc, year;

Actually, I've never use window functions in an order by with a rollup query. 实际上,我从来没有order by rollup查询order by使用窗口函数。 I wouldn't be surprised if a subquery were necessary. 如果需要子查询,我不会感到惊讶。

Try using window function max to get max of total for each year in the order by clause: 尝试使用窗口函数max以获得order by子句中每年的总数最大值:

select year, month, count(sale_id) total
from sales
group by rollup(year, month)
order by max(total) over (partition by year) desc, total desc;

I think you need to used GROUPING SETS and GROUP_ID's. 我认为您需要使用GROUPING SETS和GROUP_ID。 These will help you determine a NULL caused by a subtotal. 这些将帮助您确定由小计引起的NULL。 Take a look at the doc: https://docs.oracle.com/cd/B19306_01/server.102/b14223/aggreg.htm 看一下文档: https : //docs.oracle.com/cd/B19306_01/server.102/b14223/aggreg.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM