Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle : 'Count over Partition by' output on first row of the keyword alone

I have to query a table which will look like as follows.

select count(*) over (PARTITION BY offer_status) as count, name, status
from tablename

Output will be as:
3  |  name1  |  entered
3  |  name1  |  entered
3  |  name2  |  cleared
1  |  name3  |  completed
3  |  name3  |  cleared
3  |  name1  |  entered
3  |  name2  |  cleared


I would like to get it as :
3  |  name1  |  entered
    |  name3  |  entered
3  |  name2  |  cleared
1  |  name3  |  completed
    |  name3  |  cleared
    |  name3  |  entered
    |  name3  |  cleared


To get the count of status only for the first occurance of the keyword (of status), as it is not necessary to get the count again and again.


Or you can suggest me any other way to get it done.

like image 697
smilyface Avatar asked Feb 05 '15 15:02

smilyface


1 Answers

I would do something like:

SELECT CASE WHEN rn=1 THEN cnt END cnt, order_name, status
FROM
(
SELECT count(*) OVER (PARTITION BY status) cnt,
  ROW_NUMBER() OVER (PARTITION BY status ORDER BY order_name) rn,
  order_name,status
FROM input_table
)

See SQL Fiddle

As Gordon Linoff said, you need some sort of ordering. I ordered them by order_name but if you have some other field in the table you could use that instead.

like image 111
Zajonc Avatar answered Sep 28 '22 15:09

Zajonc