SQL - 查找两个表的行顺序的差异

时间:2009-08-07 09:58:46

标签: sql oracle sql-order-by

我有两个ID和日期表,我想按日期订购这两个表,看看那些不在同一个订单中的ID

e.g。 TABLE_1

id   |  date
------------
A       01/01/09
B       02/01/09
C       03/01/09

TABLE_2

id   |  date
------------
A       01/01/09
B       03/01/09
C       02/01/09

并获得结果

 B
 C

现在可以肯定的是,我可以通过查询转储订单的结果并区分它们,但我想知道是否有一种SQL-y方式可以获得相同的结果。

编辑澄清,表格之间的日期不一定相同,只是确定订单

由于

3 个答案:

答案 0 :(得分:3)

如果TABLE_1TABLE_2中的日期不同,则必须在其排名上加入两个表格。例如:

SQL> WITH table_1 AS (
  2     SELECT 'A' ID, DATE '2009-01-01' dt FROM dual UNION ALL
  3     SELECT 'B', DATE '2009-01-02' FROM dual UNION ALL
  4     SELECT 'C', DATE '2009-01-03' FROM dual
  5  ), table_2 AS (
  6     SELECT 'A' ID, DATE '2009-01-01' dt FROM dual UNION ALL
  7     SELECT 'C', DATE '2009-01-02' FROM dual UNION ALL
  8     SELECT 'B', DATE '2009-01-03' FROM dual
  9  )
 10  SELECT t1.ID
 11    FROM (SELECT ID, row_number() over(ORDER BY dt) rn FROM table_1) t1
 12   WHERE (ID, rn) NOT IN (SELECT ID,
 13                                 row_number() over(ORDER BY dt) rn
 14                            FROM table_2);

ID
--
B
C

答案 1 :(得分:0)

不仅仅是加入日期并且比较ID是相同的。这假设table_1是主序列。

SELECT table_1.id
FROM
  table_1
INNER JOIN table_2
    on table_1.[date] = table_2.[date]
WHERE table_1.id <> table_2.id
ORDER BY table_1.id

答案 2 :(得分:0)

ehm select id from table_1, table_2 where table_1.id = table_2.id and table_1.date <> table_2.date