Oracle左联接给予重复

时间:2019-06-27 03:38:08

标签: oracle join duplicates

我正试图从TRANS_TABLE中获取所有具有安装服务或没有安装服务的客户。

NOA-查询仅获取MAX产品,然后通过电子邮件ID重新加入TRANS_TABLE以获取所有MAX客户详细信息(他们通过添加Y或N获得安装服务,但此查询也返回与REP Product相同的内容)

下面是我的Oracel查询,它给出了重复的

with CTE as (SELECT NOA.*, 
       CASE 
         WHEN TRANS_TABLE.product_name LIKE '%Installation%' THEN 'Y' 
         ELSE 'N' 
       END AS Installaion ,
       ROW_NUMBER() OVER (PARTITION BY TRANS_TABLE.email_address ORDER BY TRANS_TABLE.email_address) AS rn

FROM   (SELECT DISTINCT email_address         
        FROM  TRANS_TABLE
        WHERE  email_address IS NOT NULL
and pdct_name like '%MAX%'      
               ) NOA 
       LEFT JOIN TRANS_TABLE 
              ON NOA.email_address = TRANS_TABLE.email_address 
              select * from cte where rn='1'

Table and the expected result

1 个答案:

答案 0 :(得分:0)

以下代码会有所帮助:

CTE AS (
    SELECT
        NOA.*,
        CASE
            WHEN TRANS_TABLE.PDCT_NAME LIKE '%INSTALLATION%' THEN 'Y' -- case sensitive name is used
            ELSE 'N'
        END AS INSTALLAION,
        ROW_NUMBER() OVER(
            PARTITION BY TRANS_TABLE.EMAIL_ADDRESS
            ORDER BY
                TRANS_TABLE.EMAIL_ADDRESS
        ) AS RN
    FROM
        (
            SELECT DISTINCT
                PDCT_NAME,
                EMAIL_ADDRESS
            FROM
                TRANS_TABLE
            WHERE
                EMAIL_ADDRESS IS NOT NULL
                AND PDCT_NAME LIKE '%MAX%'
        ) NOA
        LEFT JOIN TRANS_TABLE ON NOA.EMAIL_ADDRESS = TRANS_TABLE.EMAIL_ADDRESS
        WHERE TRANS_TABLE.PDCT_NAME NOT LIKE '%REP%') -- added this WHERE condition
SELECT
   PDCT_NAME,  EMAIL_ADDRESS, INSTALLAION
FROM
    CTE
WHERE
    RN = '1'

db<>fiddle demo

干杯!