如何在以下情况下获得最大值(SQL Server)



我有下表:

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

我想得到ID的最大值,其中CodeA001。它应该是3

这里是另一个例子:

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

在这种情况下,ID应该是1

如果我理解正确,您需要初始序列的"最后"行。基于您的问题:

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;

似乎更合理的是,'A001'不会被硬编码,而是被计算为"第一"值。

如果是这样的话:

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;

如果所有代码都相同,则需要对其进行调整。但是在您的示例数据中,您有多个值。

使用窗口功能,您可以将其表示为:

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;

如果您的DBMS支持窗口功能,以下是实现所需结果的一种方法

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

这是小提琴。

最新更新