sql >> Base de Datos >  >> RDS >> Oracle

Oracle SQL agrupa por columna con recuento, pero solo si la columna es nula o 0

esto lo hará:

SQL> select id, other_id, date_value, value, cnt from
  2   (
  3     SELECT id, other_id, date_value, value,
  4     case
  5       when other_id is null or other_id = '0' then 1
  6       else ROW_NUMBER() OVER (partition by other_id order BY Date_Value desc)
  7     end r,
  8     case
  9       when other_id is null or other_id = '0' then 1
 10       else count(*) OVER (partition by other_id)
 11     end cnt
 12     FROM some_table
 13   )
 14  where r = 1
 15  order by id;

        ID OTH DATE_VALUE               VALUE        CNT
---------- --- ------------------- ---------- ----------
         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

6 rows selected.

SQL>