我有一个表格设置如下:
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
此方法返回的数据值不正确且数据错误。
答案 0 :(得分:1)
也许你想要这个:
objectProperties: {
key(id) {
return get(awsKeys, id);
},
},
如果你只想要密钥,我会去聚合:
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
);
答案 1 :(得分:0)
使用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