Sql 基于多个字段的嵌套最小值获取行

Sql 基于多个字段的嵌套最小值获取行,sql,sql-server,Sql,Sql Server,如何根据多个字段的嵌套最小值进行查询以获取行 有一个表格,表格中有以下行: [a, b, c, id, date, line, code, d, e] id、日期、行和代码之间的关系为: one(id)->many(date)->many(line)->one(code) 希望将ID映射到与最小日期的最小行对应的代码,因此给出如下表: [a1, b1, id1, date11, line111, code1] [a2, b2,

如何根据多个字段的嵌套最小值进行查询以获取行

有一个表格,表格中有以下行:

[a, b, c, id, date, line, code, d, e]
id、日期、行和代码之间的关系为:

one(id)->many(date)->many(line)->one(code)
希望将ID映射到与最小日期的最小行对应的代码,因此给出如下表:

[a1, b1, id1, date11,            line111,             code1]
[a2, b2, id1, date12 (= date11), line122 (< line111), code2]
[a3, b3, id2, date21,            line211,             code3]
[a4, b4, id2, date22 (< date21), line221 (> line211), code4]

Where 
idX => "Xth id", 
dateXY => "Yth date of Xth id", 
and lineXYZ => "Z line of the Yth date of the Xth id".
[a2, b2, id1, date11, line122, code2]
[a4, b4, id2, date22, line221, code4]
希望这不是一个重复,因为我们无法从谷歌搜索嵌套的最小值中找到解决方案


谢谢。

让我们把这个问题分解成手头的小问题

将行号应用于[line]和[date]列,按顺序排列,使第1行为您描述的最小行

然后只需从表中选择,其中两行都是1

类似的内容是在记事本中编写的,可能无法编译,也可能无法根据您的需要进行订购:

;with c as (
    select
        id
        ,line
        ,row_number() over (partition by id order by date asc, line asc) as rn
    from
        dbo.yourTable
)

select
    id
    ,line
from
    c
where
    rn = 1

我想您只需要一个RN,…按日期ASC订购,行ASC