Teradata排名查询(左一行连接)

时间:2012-05-13 01:31:36

标签: sql left-join teradata

你是Teradata的新手,我遇到了问题

有一个ID表,用于存储给每个人的唯一ID

CREATE TABLE IDS(
ID VARCHAR(8),
UPDATED_DATE DATE)

然后我们有一个名称和地址表,没有任何存储IDS人口统计信息的主键

CREATE TABLE NAMES(
ID VARCHAR(8),
NAME VARCHAR(50))
CREATE TABLE ADRRESSES(
ID VARCHAR(8)
ADDRESS VARCHAR(200))

现在每个ID可以有多个名称和IDS。但是对于姓名和地址,我想使用那些有更多计数的人。如果两个名称具有相同的COUNT,我只想要第一行

ID NAME COUNT

1234 John Smith 6

1234约翰尼史密斯6

<12> J Smith 2

在上面的例子中,我想要名字John Smith。这是我正在执行的左连接,因为ID可能没有名称或地址。这是我正在尝试的

SELECT * FROM
(SELECT ID as V_ID from IDS) a
LEFT JOIN
(SELECT ID, NAME, COUNT(*) AS COUNTER,(RANK() OVER(ORDER BY COUNTER DESC)) AS RNK
FROM NAMES 
GROUP BY ID)b
ON a.ID = b.ID
AND b.RNK = 1            -- Should give me only the first row
LEFT JOIN
(SELECT ID, ADDRESS, COUNT(*) AS COUNTER, (RANK() OVER (ORDER BY COUNTER DESC) ) AS RNK
FROM ADDRESSES
GROUP BY ID) c
ON c.ID = a.ID
And c.RNK = 1

然而,这并没有让我得到理想的结果。我尝试使用ROW NUMBER而不是RANK,但仍然没有结果。我该如何在TERDATA中编写此查询?

1 个答案:

答案 0 :(得分:0)

我解决了......我需要qualifypartition by

SELECT * FROM
    (SELECT ID as V_ID from IDS) a
    LEFT JOIN
    (SELECT ID, NAME, COUNT(*) AS COUNTER
    FROM NAMES
    GROUP BY ID
    qualify ROW_NUMBER() OVER(PARTITION BY ID ORDER BY COUNTER DESC) = 1
    )b
    ON a.ID = b.ID
    LEFT JOIN
    (SELECT ID, ADDRESS, COUNT(*) AS COUNTER
    FROM ADDRESSES
    GROUP BY ID
    qualify ROW_NUMBER() OVER(PARTITION BY ID ORDER BY COUNTER DESC) = 1
    ) c
    ON c.ID = a.ID