Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL group by single field and count the grouped rows

Consider this table some_table:

+--------+----------+---------------------+-------+
| id     | other_id | date_value          | value |
+--------+----------+---------------------+-------+
| 1      | 1        | 2011-04-20 21:03:05 | 104   |
| 2      | 1        | 2011-04-20 21:03:04 | 229   |
| 3      | 3        | 2011-04-20 21:03:03 | 130   |
| 4      | 1        | 2011-04-20 21:02:09 | 97    |
| 5      | 2        | 2011-04-20 21:02:08 | 65    |
| 6      | 3        | 2011-04-20 21:02:07 | 101   |
| ...    | ...      | ...                 | ...   |
+--------+----------+---------------------+-------+

I want to select and group by the other_id, so that I only get unique other_ids. This query works (credit @MichaelPakhantsov):

select id, other_id, date_value, value from
 (
   SELECT id, other_id, date_value, value, 
   ROW_NUMBER() OVER (partition by other_id order BY Date_Value desc) r
   FROM some_table 
 )
 where r = 1

How can I get the same result, but with a count of how many rows were grouped, for each other_id. The desired result would look like:

+--------+----------+---------------------+-------+-------+
| id     | other_id | date_value          | value | count |
+--------+----------+---------------------+-------+-------+
| 1      | 1        | 2011-04-20 21:03:05 | 104   | 3     |
| 5      | 2        | 2011-04-20 21:02:08 | 65    | 2     |
| 3      | 3        | 2011-04-20 21:03:03 | 130   | 2     |
+--------+----------+---------------------+-------+-------+

I've tried using COUNT(other_id) in both the inner and outer selects but it produces this error:

ORA-00937: not a single-group group function


Note: similar to this question (example table and answer taken from there) but that question doesn't give a count of the collapsed rows.

like image 423
ServerBloke Avatar asked Feb 17 '23 20:02

ServerBloke


1 Answers

add a

count(*) OVER (partition by other_id) cnt

to the inner query

select id, other_id, date_value, value, cnt from
 (
   SELECT id, other_id, date_value, value, 
   ROW_NUMBER() OVER (partition by other_id order BY Date_Value desc) r,
   count(*) OVER (partition by other_id) cnt
   FROM some_table 
 )
 where r = 1
like image 73
DazzaL Avatar answered Feb 20 '23 08:02

DazzaL