2

我正在访问的数据库有两个需要使用 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'
4

2 回答 2

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 中非常快。

于 2013-01-25T15:52:35.240 回答
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'
于 2013-01-25T15:49:22.653 回答