简体   繁体   中英

select the maximum date with condition

I have below table

Date Col3
10/22/2020 C
10/23/2020 V

I want a query to get the maximum date where col3='C'. If there is 'V' in col 3 with maximum date then the output should be null

select max(date) from table where col3='C' . Then we will get output as 10/22/2020, but in the table we have one more values V with 10/23/2020.

So in this case if I write select max(date) from table where col3='C' I should get output as null.

I tried different ways but not working, please help me.

If the condition is that a row with 'V' can exist, as long as its date is before the max(date) for 'C' then:

select T1.adate_max from
    (select max(adate) as adate_max
    from A 
    where col3 = 'C') T1 
left join A on A.adate >= T1.adate_max and A.col3 = 'V'
where A.col3 is null

This alternative will return the maximum date for col3='C' as long as there is a not another row with that same maximum date with col3='V'

select T1.adate_max from
    (select max(adate) as adate_max
    from A 
    where col3 = 'C') T1 
left join A on A.adate = T1.adate_max and A.col3 = 'V'
where A.col3 is null

there must be a cleaner way to write it but it works :

SELECT CASE WHEN (SELECT col3 FROM A WHERE adate=(SELECT max(adate) FROM A))='V' THEN NULL ELSE max(adate) END
FROM A

You can test it here : https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=c2678aec931a95ad3d0ee4c3f8eafe4a

I think this is what you wanted.

Get maximum date for Col3 = C

If the row with maximum date is Col3 = V return NULL


with
cte as
(
    select  *,
            rn = row_number() over (order by [Date] desc)
    from    yourtable
) 
select  max([Date])
from    cte
where   Col3    = 'C'
and     not exists
        (
            select  *
            from    cte 
            where   rn  = 1
            and     Col3    = 'V'
        )

Assuming that there are only "C"s and "V"s in the column, you can just use conditional logic:

select (case when max(case when Col3 = 'C' then date end) = max(date)
             then max(date)
        end)
from t;

This returns the maximum date specifically when the maximum date is "C".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM