如何创建一个 SQL 查询来检查多个表中的重复项
How to create an SQL query that checks for duplicates in multiple tables
我想创建一个 SQL 查询,用于检查多个不同的 table 中是否存在重复项。我在 Teradata 中这样做。我希望输出如下所示。
|Table A| |Table B| |Table C| |Table D| |Table D|
对于这些列中的每一列,我们可以获得值 Y
或 N
。
(Y means that duplicates exist, N means that duplicates does not exist).
我如何创建这个脚本
我已经设法编写了如何在 table:
中检查重复项的代码
SELECT Customer_Id, Year_Month_Id, count(*)
FROM A
GROUP BY 1,2
HAVING count(*)>1)
编辑#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
编辑:
在单个 table:
中查找重复项
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
如果您要查找两个 table 之间的重复项,我可能会使用 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
我想创建一个 SQL 查询,用于检查多个不同的 table 中是否存在重复项。我在 Teradata 中这样做。我希望输出如下所示。
|Table A| |Table B| |Table C| |Table D| |Table D|
对于这些列中的每一列,我们可以获得值 Y
或 N
。
(Y means that duplicates exist, N means that duplicates does not exist).
我如何创建这个脚本 我已经设法编写了如何在 table:
中检查重复项的代码SELECT Customer_Id, Year_Month_Id, count(*)
FROM A
GROUP BY 1,2
HAVING count(*)>1)
编辑#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
编辑: 在单个 table:
中查找重复项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
如果您要查找两个 table 之间的重复项,我可能会使用 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