简体   繁体   中英

How to get max value in below case (SQL Server)

I have the following table:

ID      Code
1       A001
2       A001
3       A001
4       A002
5       A001
6       A002

I want to get the max value of ID where Code is A001 . It should be 3 .

Here is another example:

ID      Code
1       A001
2       A002
3       A001
4       A002
5       A001
6       A002

In this case, ID should be 1 .

Your question is not cleared to me. Can you add some more details or any other example.

If your DBMS supports window function, Here is 1 way to achieve the desired result

SELECT MAX(ID), CODE
FROM (SELECT D.ID, D.CODE, D.ID - ROW_NUMBER() OVER(PARTITION BY D.CODE ORDER BY D.ID) RN
      FROM DATA_TABLE D
      WHERE CODE = 'A001') X
WHERE RN = 0
GROUP BY CODE

Here is the fiddle.

If I understand correctly, you want the "last" row of the initial sequence. Based on your question:

select t.*
from t
where t.id < (select min(t2.id)
              from t t2
              where t2.code <> 'A001'  -- not NOT EQUALS
             ) 
order by t1.id desc;

It seems more reasonable that 'A001' would not be hard-coded but calculated as the "first" value.

If that is the case:

select t.*
from t cross join
     (select top (1) t.*
      from t
      order by t.id
     ) top1
where t.id < (select min(t2.id)
              from t t2
              where t2.code <> top1.id  -- not NOT EQUALS
             ) 
order by t1.id desc;

This needs to be tweaked if all codes are the same. But in your sample data you have multiple values.

With window functions, you can express this as:

select top (1) t.*
from (select t.*,
             min(case when code <> first_code then id end) over () as first_notcode_id
      from (select t.*,
                   first_value(code) over (order by id) as first_code
            from t
           ) t
     ) t
where first_notcode_id is null or
      id < first_notcode_id
order by id;

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