In a nutshell I’m trying to group by a column but only if that column is not null or 0 in which case I still want to get those rows, but just not grouped. I have this table some_table:
+--------+----------+---------------------+-------+
| id | other_id | date_value | value |
+--------+----------+---------------------+-------+
| 1 | abc | 2011-04-20 21:03:05 | 104 |
| 2 | abc | 2011-04-20 21:03:04 | 229 |
| 3 | xyz | 2011-04-20 21:03:03 | 130 |
| 4 | abc | 2011-04-20 21:02:09 | 97 |
| 5 | 0 | 2011-04-20 21:02:08 | 65 |
| 6 | xyz | 2011-04-20 21:02:07 | 101 |
| 7 | | 2011-04-20 21:02:07 | 200 |
| 8 | 0 | 2011-04-20 21:02:07 | 201 |
| 9 | | 2011-04-20 21:02:07 | 202 |
+--------+----------+---------------------+-------+
I wanted to select the rows and group by other_id, and also include a count of the grouped rows. This query works:
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
The result is:
+--------+----------+---------------------+-------+-------+
| id | other_id | date_value | value | count |
+--------+----------+---------------------+-------+-------+
| 1 | abc | 2011-04-20 21:03:05 | 104 | 3 |
| 3 | xyz | 2011-04-20 21:03:03 | 130 | 2 |
| 5 | 0 | 2011-04-20 21:02:08 | 65 | 2 |
| 7 | | 2011-04-20 21:02:07 | 200 | 2 |
+--------+----------+---------------------+-------+-------+
The problem is, I don’t want to group the rows that have other_id of null or 0. So the desired result is this:
+--------+----------+---------------------+-------+-------+
| id | other_id | date_value | value | count |
+--------+----------+---------------------+-------+-------+
| 1 | abc | 2011-04-20 21:03:05 | 104 | 3 |
| 3 | xyz | 2011-04-20 21:03:03 | 130 | 2 |
| 5 | 0 | 2011-04-20 21:02:08 | 65 | 1 |
| 7 | | 2011-04-20 21:02:07 | 200 | 1 |
| 8 | 0 | 2011-04-20 21:02:07 | 201 | 1 |
| 9 | | 2011-04-20 21:02:07 | 202 | 1 |
+--------+----------+---------------------+-------+-------+
As you can see, everything is grouped except when other_id is null or 0 in which case they are still selected, but not grouped. I am also trying to order by the date_value.
I have tried adding a WHERE clause in the OVER clause:
OVER (partition by other_id WHERE other_id IS NOT NULL AND other_id IS NOT '0' order BY Date_Value desc)
-- this produces an error: ORA-00907: missing right parenthesis
I have thought about doing a second select query and trying to stack the first results on top of the second, but I don’t think that would work because of the ordering.
Is there any way of grouping like this with a condition?
this will do it: