2

Есть таблица вида

shipment     order      date_start
---------------------------------------------
shipment1    order1     01-01-2019
shipment1    order2     null
shipment2    order3     05-01-2019
shipment2    order4     02-01-2019

Как сделать выборку так, чтобы при присутствии хотя бы одного null в группе, выводился null.

Т.е. в запросе вида

select shipment, max(date_start) from table group by shipment;

надо вывести

shipment1    null
shipment2    05-02-2019
1
  • select t1.shipment, max( case when exists( select 1 from table t2 where t2.date_start is null and t1.shipment=t2.shipment ) then null else t1.date_start end ) from table t1 group by t1.shipment 21 мая 2019 в 16:03

3 ответа 3

6

Думаю так:

with data (shipment, orderno, date_start) as (
    select 'shipment1', 'order1', date'2019-01-01' from dual union all
    select 'shipment1', 'order2', null             from dual union all
    select 'shipment2', 'order3', date'2019-01-05' from dual union all
    select 'shipment2', 'order4', date'2019-01-02' from dual 
)
select shipment, max (date_start) keep (dense_rank first order by date_start desc) maxdate
from data
group by shipment
;

SHIPMENT  MAXDATE                      
--------- -----------------------------
shipment1 null                             
shipment2 2019-01-05 00:00:00          

Агрегатные функции с KEEP есть только в Oracle СУБД. Более стандартный запрос, который вернёт тот же результат:

select shipment, date_start maxdate
from (
    select 
        d.*, 
        row_number () over (partition by shipment order by date_start desc nulls first) rn
    from data d
)
where rn = 1
;
3
SELECT DISTINCT 
    shipment, 
    FIRST_VALUE(date_start) 
        OVER (PARTITION BY shipment 
              ORDER BY date_start DESC NULLS FIRST)
FROM table

введите сюда описание изображения

1
  • Код CTE честно украден из ответа товарища 0xdb.
    – Akina
    21 мая 2019 в 18:25
1
select shipment,case count(*) when count(date_start) then max(date_start) end 
from t group by shipment;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.