如何创建一个SQL查询来检查多个表中的重复项

时间:2015-03-13 12:27:15

标签: sql teradata

我想创建一个SQL查询,我在其中检查是否存在多个不同表中的重复项。我是在Teradata做的。我希望输出看起来如下所示。

|Table A| |Table B| |Table C| |Table D| |Table D| 

对于这些列中的每一列,我们都可以获得值YN

  

(Y表示存在重复项,N表示不存在重复项)。

如何创建此脚本 我设法编写了如何在表中检查重复项的代码:

SELECT  Customer_Id, Year_Month_Id, count(*)
FROM    A
GROUP BY 1,2
HAVING count(*)>1)

1 个答案:

答案 0 :(得分:0)

编辑#2:

 SELECT
 *
 FROM

     (SELECT
    CASE WHEN MAX(cnt) >1 THEN 'Y' ELSE 'N' END AS [Table1]
        FROM
        (
        SELECT 
        customer_id,
        year_month_id,
        COUNT (*) AS Cnt
        FROM
        table1
        GROUP BY 1,2
        ) tbl1 
    ) t1
CROSS JOIN
     (SELECT
    CASE WHEN MAX(cnt) >1 THEN 'Y' ELSE 'N' END AS [Table2]
        FROM
        (
        SELECT 
        customer_id,
        year_month_id,
        COUNT (*) AS Cnt
        FROM
        table2
        GROUP BY 1,2
        ) tbl2
    ) t2

编辑: 要在单个表中查找重复项:

select
customer_id,
year_month_id,
case when cnt >1 then 'Y' else 'N' end
from
(
select 
customer_id,
year_month_id,
count (*) as Cnt
from
table1
group by 1,2
) t

如果您正在寻找两个表之间的重复项,我可能会使用union all,如下所示:

 select
    customer_Id,
    year_month_id
    case when count(*) > 1 then 'Y' else 'N' end
    from
    (
    select distinct
    customer_id,
    year_month_id
    from
    table1
    group by 1,2
    UNION ALL
    select distinct
    customer_id,
    year_month_id
    from
    table2 )t 
    group by 1,2