在Oracle Sql上使用不同条件在同一个表上列出对

时间:2016-09-27 19:17:12

标签: sql oracle

我需要列出成对的客户名称,如下所示;

> CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME

这样每对客户都有相同的邮政编码(也在客户表中)。

在任务上有一个提示

  

提示:您的输出应该有四列:CUSTOMER_FIRST_NAME,CUSTOMER_LAST_NAME,CUSTOMER_FIRST_NAME,CUSTOMER_LAST_NAME

这是我到目前为止所写的:

SELECT DISTINCT CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME
FROM CUSTOMERS
WHERE CUSTOMER_ZIP = CUSTOMER_ZIP

但我不确定如何继续,因为我昨天才开始学习SQL。我也尝试加入同一个表格,导致模糊错误。

更新#1: 我按照@ kpater87

的建议使用别名编写了这段代码
 SELECT DISTINCT  C1.CUSTOMER_FIRST_NAME, C1.CUSTOMER_LAST_NAME , C2.CUSTOMER_FIRST_NAME, C2.CUSTOMER_LAST_NAME 
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP

但即使我有一个明确的声明,它也会显示重复的数据。这是预期还是我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的更新查询看起来很好。您的查询中唯一的问题是它将加入相同的记录。 如果表格中有主键,则可以通过添加WHERE条件来改进查询:

SELECT DISTINCT C1.CUSTOMER_FIRST_NAME,
  C1.CUSTOMER_LAST_NAME ,
  C2.CUSTOMER_FIRST_NAME,
  C2.CUSTOMER_LAST_NAME
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
WHERE C1.PK <> C2.PK;

PK - 是表中主键的列。

如果您没有主键,可以试试这个:

SELECT C1.CUSTOMER_FIRST_NAME,
  C1.CUSTOMER_LAST_NAME ,
  C2.CUSTOMER_FIRST_NAME,
  C2.CUSTOMER_LAST_NAME
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
WHERE C1.CUSTOMER_FIRST_NAME <> C2.CUSTOMER_FIRST_NAME
  AND C2.CUSTOMER_LAST_NAME <> C2.CUSTOMER_LAST_NAME

但是仍有一个问题,在你的输出中你会得到例如。

Mary Smith James Bond
James Bond Mary Smith

删除排列:

SELECT C1.CUSTOMER_FIRST_NAME,
  C1.CUSTOMER_LAST_NAME ,
  C2.CUSTOMER_FIRST_NAME,
  C2.CUSTOMER_LAST_NAME,
  C1.CUSTOMER_ZIP
FROM T_CUSTOMERS C1
LEFT JOIN T_CUSTOMERS C2
ON (C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
    AND
    C1.CUSTOMER_NUMBER > C2.CUSTOMER_NUMBER );

另请参阅:SQL: self join using each rows only once