如何在加入前对数据进行排序

时间:2012-10-26 17:46:34

标签: sql sql-server

尝试对具有相同数据布局的2个表进行差异,并在同一行上具有不匹配记录

Table1                   Table2
------                   ------

CUSTOMER PART            CUSTOMER  PART

CUSTID1  PART1           CUSTID1  PART1
CUSTID1  PART2           CUSTID1  PART2
CUSTID1  PART3           CUSTID1  PART3
CUSTUD1  PART4


SELECT T1.CUSTID, T1.PART, T2.CUSTID, T2.PART FROM TABLE1 AS T1
LEFT JOIN TABLE2 AS T2 ON T1.CUSTID = T2.CUSTID
WHERE  T1.PART <>  T2.PaRT
ORDER BY T1.CUSTID 

有时输出如下所示 - 当没有输出时显示不匹配。 我是否在联接之前对表格进行排序以使数据排成一行?

由于

CUSTID1  PART1           CUSTID1  PART3
CUSTID1  PART2           CUSTID1  PART1
CUSTID1  PART3           CUSTID1  PART2
CUSTUD1  PART4           NULL     NULL

2 个答案:

答案 0 :(得分:1)

您需要执行以下操作:

SELECT T1.CUSTID, T1.PART, T2.CUSTID, T2.PART 
FROM TABLE1 AS T1 
     INNER JOIN TABLE2 AS T2 ON T1.CUSTID = T2.CUSTID 
WHERE T1.PART <> T2.PaRT

无需使用左外连接。 order by子句对连接的结果没有任何影响;它只是命令结果。

答案 1 :(得分:0)

您当前的查询,即使是样本数据,也应该为您提供大量数据:

SELECT T1.CUSTID, T1.PART, T2.CUSTID, T2.PART FROM TABLE1 AS T1
LEFT JOIN TABLE2 AS T2 ON T1.CUSTID = T2.CUSTID
WHERE  T1.PART <>  T2.PaRT
ORDER BY T1.CUSTID 

预期结果:

CUSTID1    PART1    CUSTID1    PART2
CUSTID1    PART1    CUSTID1    PART3
CUSTID1    PART2    CUSTID1    PART1
CUSTID1    PART2    CUSTID1    PART3
CUSTID1    PART3    CUSTID1    PART1
CUSTID1    PART3    CUSTID1    PART2
CUSTID1    PART4    CUSTID1    PART1
CUSTID1    PART4    CUSTID1    PART2
CUSTID1    PART4    CUSTID1    PART3

你可能想要一个条件为ON T1.CustID = T2.CustID AND T1.Part = T2.Part的FULL OUTER JOIN。如果你不能做FULL,使用LEION和RIGHT联接的UNION。或者,如果您不担心Table2中的行与Table1中没有对应的行,那么只有具有增强的ON子句的现有LEFT JOIN才会这样做。

如果您想要所有匹配的行和所有不匹配的行,则使用

SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
  FROM Table1 AS T1
  FULL OUTER JOIN Table2 AS T2
       ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part

如果您只想查看不匹配的行,请写下:

SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
  FROM Table1 AS T1
  FULL OUTER JOIN Table2 AS T2
       ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
 WHERE T1.Part IS NULL OR T2.Part IS NULL

LEFT-UNION-RIGHT查询(适用于所有行)可能是:

SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
  FROM Table1 AS T1
  LEFT OUTER JOIN Table2 AS T2
       ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part
UNION
SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
  FROM Table1 AS T1
 RIGHT OUTER JOIN Table2 AS T2
       ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part

所有行的LEFT only查询可能是:

SELECT T1.CustID, T1.Part, T2.CustID, T2.Part
  FROM Table1 AS T1
  LEFT OUTER JOIN Table2 AS T2
       ON T1.CustID = T2.CUSTID AND T1.Part = T2.Part

如果您只想查看不匹配的行,可以添加适当的WHERE过滤条件。 (显然,如果你只想看到匹配的行,你可以使用常规的INNER JOIN或只是JOIN。)

Caveat Emptor :没有DBMS验证过这个SQL。