【发布时间】:2014-06-03 00:09:41
【问题描述】:
提前致谢:请考虑以下表格:
Table 1: matrix_data
Matrix_ID Data_ID DATE(Date) Info(varchar)
1 1 3000 A
1 1 3500 B
1 2 3600 C
1 2 3700 D
2 1 3100 E
2 1 3400 F
2 2 3450 G
2 2 3750 H
3 1 3000 I
3 1 3500 J
3 2 3620 K
3 2 3700 L
4 1 3100 M
4 1 3400 N
4 2 3450 O
4 2 3750 P
Table 2: Result_Query
Result_ID Matrix_ID
22 1
22 3
鉴于以下 -
A Date (for example - 3640)
A Data_ID (For example - 2)
A Result_ID (For example - 22)
我需要一个查询,该查询将为每个具有与 Result_ID (22) 对应的记录的 Matrix_id 返回一行。 对于也与提供的 Data_ID (2) 匹配的记录,该行应包含最大 DATE
For the example provided, the result would be :
Matrix_ID Data_ID DATE Info(varchar)
1 2 3600 C
3 2 3620 K
我无法更改表格。这是一个小例子,但我可能在 Result_ID 中有 5000 个矩阵 ID,所以我喜欢这样做,而不需要为每条记录都访问数据库。 存储过程是一个选项,如果我可以使用直接 sql 更好。 我正在使用甲骨文。 DATE 是日期列而不是数字。再次感谢 -
到目前为止 - 我试图简化问题并只是这样做:
select *
from ( select b.* , rank() over ( partition by data_id, matrix_id order by DATE desc ) rnk
from matrix_data b )
where rnk = 1
我现在需要折叠其余的约束
【问题讨论】:
-
嗯,你试过什么?
-
感谢@Barmar 对问题进行分类 - 到目前为止,我试图通过获得排名来简化问题 - 但没有得到任何记录。需要阅读 Rank() / Partition,这对我来说是新的。
标签: sql oracle greatest-n-per-group