我有一个表设置如下:
Key || Code || Date
5 2 2018
5 1 2017
8 1 2018
8 2 2017
我只需要检索密钥和代码,其中:
Code=2 AND Date > the other record's date
所以根据上面的数据,我需要检索:
Key 5 with code=2
密钥8不符合标准,因为代码2的日期低于代码1的日期
我尝试自己加入表,但这返回了不正确的数据
Select key,code
from data d1
Join data d2 on d1.key = d2.key
Where d1.code = 2 and d1.date > d2.date
此方法返回的数据值不正确,数据错误。
也许你想要这个:
select d.*
from data d
where d.code = 2 and
d.date > (select d2.date
from data d2
where d2.key = d.key and d2.code = 1
);
如果你只想要密钥,我会去聚合:
select d.key
from data d
group by d.key
having max(case when d2.code = 2 then date end) > max(case when d2.code <> 2 then date end);
使用row_number
,你可以按升序选择日期行。这基于您的样本数据,选择2行
DECLARE @table TABLE ([key] INT, code INT, DATE INT)
INSERT @table
SELECT 5, 2, 2018
UNION ALL
SELECT 5, 2, 2018
UNION ALL
SELECT 8, 1, 2018
UNION ALL
SELECT 8, 2, 2017
SELECT [key], code, DATE
FROM (
SELECT [key], code, DATE, ROW_NUMBER() OVER (
PARTITION BY [key], code ORDER BY DATE
) rn
FROM @table
) x
WHERE rn = 2