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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With