简体   繁体   English

加入表格中的最大日期

[英]Joining with max date from table

SELECT COL1,
    COL2,
    COL3
FROM TABLE1,
    TABLE2,
    TABLE3,
    TABLE4
WHERE TABLE1.KEY1 = TABLE2.KEY1
    AND TABLE2.KEY = TABLE3.KEY
    AND TABLE2.FILTER = 'Y'
    AND TABLE3.FILTER = 'Y'
    AND TABLE2.KEY = TABLE3.KEY
    AND TABLE3.KEY = TABLE4.KEY

I have a similar query and I need to do modification, in a table 3 there is a date column and I need to pick highest day value row for joining. 我有一个类似的查询,我需要进行修改,在表3中有一个date列,我需要选择日最高值行来加入。 Lets say there are 4 rows from table number 3 which are getting satisfied for join, I need to pick highest date row out of those 4 for joining purpose and then show the result. 可以说表号3中有4行对联接感到满意,我需要从这4个表中选择最高日期的行以进行联接,然后显示结果。

Hope question is clear. 希望问题很明确。 Database oracle 10g 数据库Oracle 10g

Try something like this query. 尝试类似此查询的操作。

SELECT
    COL1,
    COL2,
    COL3,
    T33.*

FROM TABLE1

JOIN TABLE2 ON TABLE1.KEY1 = TABLE2.KEY1

JOIN TABLE4 ON TABLE2.KEY = TABLE4.KEY

JOIN

(
    SELECT MAX(T.Day) as DT, T.KEY
    FROM TABLE3 T
    WHERE T.FILTER = 'Y'
    GROUP BY T.KEY
) T3 on TABLE4.KEY = T3.KEY

JOIN TABLE3 T33 ON T3.KEY = T33.KEY AND T3.DT = T33.Day

WHERE

TABLE2.FILTER = 'Y'

The main idea is that instead of 主要思想是
joining to TABLE3 you do this: 加入TABLE3您可以执行以下操作:

SELECT MAX(T.Day) as DT, T.KEY
FROM TABLE3 T
WHERE T.FILTER = 'Y'
GROUP BY T.KEY

give that table/recordset a name and join to it instead. 给该表/记录集一个名称,然后加入该表/记录集。

Then you can join again to the original TABLE3 (see T33 ) 然后,您可以再次加入原始的TABLE3 (请参阅T33
to pull all the other needed columns from TABLE3 which are TABLE3拉出所有其他需要的列
not present in T3 . T3不存在。

You can work out the other details, I think. 我认为,您可以制定其他细节。

To minimally modify your current query, you can add a condition in your WHERE clause 要最小化修改当前查询,可以在WHERE子句中添加条件

AND TABLE3.DATE = (SELECT MAX(DATE) FROM TABLE3 WHERE TABLE3.FILTER = 'Y')

Although in the future I recommend using explicit JOINS. 尽管将来我建议使用显式JOINS。

SELECT COL1,
    COL2,
    COL3
FROM TABLE1 
    INNER JOIN TABLE2 ON TABLE1.KEY1 = TABLE2.KEY1
    INNER JOIN TABLE3 ON TABLE2.KEY = TABLE3.KEY
    INNER JOIN TABLE4 ON TABLE3.KEY = TABLE4.KEY
WHERE 
    TABLE2.FILTER = 'Y'
    AND TABLE3.FILTER = 'Y'
    AND TABLE3.DATE = (SELECT MAX(DATE) FROM TABLE3 WHERE TABLE3.FILTER = 'Y')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM