基于特定字段值的SQL选择

时间:2018-08-31 20:29:37

标签: sql db2 rpg

我有一个人表和一个他们的地址表。一个人可以有多个地址,但是每个地址都有一个生效日期。

我想将人员和地址链接到他们的最大生效日期,我在下面附加我的查询。我只得到整个表中的最大有效日期。请注意,这是RPG,因此日期像数字一样存储,例如今天将是YYYYMMDD格式(2018-08-31)为20180831。

 SELECT 
   PERSON.ID, PERSON.NAME, ADDRESS.ID, ADDRESS.ADD1
 , ADDRESS.ADD2, ADDRESS.CITY 
   FROM PERSON
   LEFT JOIN 
     (
      SELECT * 
        FROM ADDRESS
          WHERE EFF_DATE IN (SELECT MAX(EFF_DATE) FROM ADDRESS)
     ) AS A
   ON PERSON.ID = A.ID

我知道问题出在WHERE子句中,但是我正在画空白。

3 个答案:

答案 0 :(得分:1)

您需要在表LEFT OUTER JOIN和表person之间使用address,并添加地址必须与最后一个eff_date相匹配。

您没有说数据库是什么,但是考虑到您将其标记为RPG,我认为是DB2:

with d as (
  select person_id, max(eff_date) as max_date 
    from address 
    group by person_id
)
select p.*
  from person p
  left join address a on p.id = a.person_id
    and (a.person_id, a.eff_date) in (
      select person_id, max_date from d
    )

答案 1 :(得分:1)

Impaler有一个很好的解决方案,但是我可以通过删除子查询来改进它:

with d as (
  select person_id, max(eff_date) as max_date 
    from address 
    group by person_id
)
select p.*
  from person p
  left join d on p.id = d.person_id
  left join address a 
    on p.id = a.person_id and a.eff_date = d.max_date

答案 2 :(得分:0)

IRL,我将查看最近的地址。

def send(data: Email): String

  override def send(data: JEmail): String = {
    val email = convert(data)
    send(email)
  }

然后,您可以简单地查询人和最近的地址

create view recentaddress as 
    select a.* from address a 
      join ( 
       select address.id, max(eff_date) md from address
        group by address.id 
        ) as b 
        on a.id = b.id and a.eff_date= b.md    

或者您可以构建一个整体。

select * from person a left join recentaddress b on a.person_id = b.id