Oracle - 获取组的行号

时间:2016-03-18 13:04:16

标签: oracle count row grouping

我有下面的SQL用于获取行号。我想知道的是知道特定组中有多少行。这可能吗?

由于

   select 
          to_char(ndt.dt , 'yyyy'), 
          to_char(ndt.dt , 'MON'), 
          to_char(ndt.dt , 'dd'),  
          row_number() OVER (partition by to_char(ndt.dt , 'yyyy'), to_char(ndt.dt , 'MON') ORDER BY ndt.dt)    

          from (
            (SELECT TRUNC (SYSDATE - ROWNUM + 44) dt
             FROM DUAL CONNECT BY ROWNUM < 91
             order by dt asc) ndt
          );

但是这给了我

  1. | 2016 | APR | 01 | 1 |
  2. | 2016 | APR | 02 | 2 |
  3. ...
  4. | 2016 | APR | 30 | 30 |
  5. | 2016 | MAY | 01 | 1 |
  6. | 2016 | MAY |
  7. 而我真正想要的是

    1. | 2016 | APR | 01 | 30 |
    2. | 2016 | APR | 02 | 30 |
    3. ...
    4. | 2016 | APR | 30 | 30 |
    5. | 2016 | MAY | 01 | 31 |
    6. | 2016 | MAY | 31 |

1 个答案:

答案 0 :(得分:1)

您可以尝试使用count代替row_number

select to_char(d, 'yyyy'), to_char(d, 'mon'), to_char(d, 'dd'),
       count(1) over ( partition by extract(month from d)) as count
from (
        select to_date('01042016', 'ddmmyyyy') + level -1 as d
        from dual
        connect by level <= 61
     )
order by 1, 2, 3 

你的+44背后的逻辑对我来说并不是那么清楚,所以我使用了一个简单的开始日期