Search code examples
plsqloracle11grownum

How can we count the PK and repeat this count for the entire list of PK?


How can we count the PK and repeat this count for the entire list of PK?

For example:

Table A (that contains 3000 registers, for example)

ID
0001
0002
0003
0004
0005
...

Using without any filter, we expect:

COUNT(*) | ID
3000     | 0001
3000     | 0002
3000     | 0003
3000     | 0004
3000     | 0005
...

Bt when using filters to restric the results, the COUNT must reflect according the result in screen for example:

select ...
where ID IN (0001,0002,0003,0004,0005)

Then should be:

COUNT(*) | ID
5        | 0001
5        | 0002
5        | 0003
5        | 0004
5        | 0005

This appears to be very simple, but I'm not able to do this.

I've tried to use rownum, count(PK), max(rownum) and haven't success.

Thanks


Solution

  • This?

    SQL> select count(*) from emp;
    
      COUNT(*)
    ----------
            12
    
    SQL> select empno, count(*) over (order by null) cnt from emp;
    
         EMPNO        CNT
    ---------- ----------
          7369         12
          7499         12
          7521         12
          7566         12
          7654         12
          7698         12
          7782         12
          7839         12
          7844         12
          7900         12
          7902         12
          7934         12
    
    12 rows selected.
    
    SQL> select empno, count(*) over (order by null) cnt from emp where deptno = 10;
    
         EMPNO        CNT
    ---------- ----------
          7782          3
          7839          3
          7934          3
    
    SQL>