DB2 SQL Join和Max值

时间:2013-01-25 15:40:58

标签: sql join db2 max

我正在访问的数据库有两个我需要使用DB2 SQL查询的表,这里显示为nametable和addresstable。该查询用于查找具有特定余额的所有人。地址存储在单独的表中以跟踪地址变化。在addresstable中,最新地址由序列号(ADDRSEQUENCE)确定。 AddressID字段存在于两个表中,并且将每个人与特定地址联系起来。最高序列号是当前地址。我需要每个人的当前地址,只需要那个。我知道我将不得不在某处使用MAX作为序列号,但我无法弄清楚如何在给定连接的情况下定位它。这是我当前的查询,当然返回所有地址......

SELECT NAMETABLE.ACCTNUM AS ACCOUNTNUMBER, 
NAMETABLE.NMELASTBUS AS LASTNAME,
NAMETABLE.NAME_FIRST AS FIRSTNAME, 
NAMETABLE.BALDUE AS BALANCEDUE,
ADDRESSTABLE.STREETNAME AS ADDR, 
ADDRESSTABLE.ADDRLINE2 AS 
ADDRLINE2,ADDRESSTABLE.CITYPARISH AS CITY, 
ADDRESSTABLE.ADDRSTATE AS STATE,
ADDRESSTABLE.ZIPCODE AS ZIP, 
ADDRESSTABLE.ADDIDSEQNO AS ADDRSEQUENCE
FROM NAMETABLE JOIN ADDRESSTABLE ON NAMETABLE.ADDRESSID = ADDRESSTABLE.ADDRESSID
WHERE NAMETABLE.BALANCEDUE >= '50.00'

2 个答案:

答案 0 :(得分:3)

您可以像MAX(ADDRSEQUENCE)那样进行子选择:

SELECT 
     N.ACCTNUM AS ACCOUNTNUMBER
    ,N.NMELASTBUS AS LASTNAME
    ,N.NAME_FIRST AS FIRSTNAME
    ,N.BALDUE AS BALANCEDUE
    ,A.STREETNAME AS ADDR, 
    ,A.ADDRLINE2 AS 
    ,A.ADDRLINE2
    ,A.CITYPARISH AS CITY, 
    ,A.ADDRSTATE AS STATE,
    ,A.ZIPCODE AS ZIP, 
FROM NAMETABLE AS N 
JOIN ADDRESSTABLE AS A 
  ON N.ADDRESSID = A.ADDRESSID
WHERE N.BALANCEDUE >= '50.00'
  AND A.ADDRSEQUENCE = (
    SELECT MAX(ADDRSEQUENCE)
    FROM ADDRESSTABLE AS A2
    WHERE A.ADDRESSID = A2.ADDRESSID
)

这在DB2中非常快。

答案 1 :(得分:0)

您可以使用row_number和partition by来执行此操作。像这样:

with orderedaddress as (
 select row_number() over (partition by ADDRESSID order by ADDRSEQUENCE desc) as rown,
 STREETNAME,ADDRESSID, ... from ADDRESSTABLE 
)
select NAMETABLE.ACCTNUM AS ACCOUNTNUMBER,
...
oa.STREETNAME 
...
from NAMETABLE JOIN orderedaddress oa on NAMETABLE.ADDRESSID = oa.ADDRESSID
where oa.rown = 1
and NAMETABLE.BALANCEDUE >= '50.00'