替换两个MINUS / EXCEPT查询

时间:2013-06-18 16:47:00

标签: sql oracle

当确认转向存储过程没有制动其预期功能时(A点的数据到达B点),我经常在SQL Server中使用MINUSEXCEPT)。然而,这迫使我运行每个查询两次(因为减去返回第一个/顶部表中存在的第二个/底部不存在的行):

SELECT value1, value2, value3 FROM table1 WHERE uploadID = 'beforeTurning'
MINUS
SELECT value1, value2, value3 FROM table1 WHERE uploadID = 'afterTurning';

SELECT value1, value2, value3 FROM table1 WHERE uploadID = 'afterTurning'
MINUS
SELECT value1, value2, value3 FROM table1 WHERE uploadID = 'beforeTruning';

我可以用一个查询完成同样的事情吗?我该怎么做?

2 个答案:

答案 0 :(得分:1)

SELECT 
  value1, value2, value3,
  sum(decode(uploadID, 'afterTurning', 1, 'beforeTurning', -1)) AS diff
FROM table1 
GROUP BY value1, value2, value3
HAVING sum(decode(uploadID, 'afterTurning', 1, 'beforeTurning', -1)) <> 0

答案 1 :(得分:0)

这是一种方式:

WITH
  BeforeAfter AS (
    SELECT * FROM table1 WHERE uploadID = 'beforeTunning'
    MINUS SELECT * FROM table1 WHERE uploadID = 'afterTunning'),
  AfterBefore AS (
    SELECT * FROM table1 WHERE uploadID = 'afterTunning'
    MINUS SELECT * FROM table1 WHERE uploadID = 'beforeTunning')
SELECT * FROM BeforeAfter
UNION ALL SELECT * FROM AfterBefore

UNION可能比UNION ALL - 你的电话更适合你。