改进查询以查找两个表之间的不同步值

时间:2012-07-20 00:19:06

标签: sql postgresql

我有以下查询:

SELECT
  tableOneId
  SUM(a+b+c) AS tableOneData,
  MIN(d) AS tableTwoData,
FROM
  tableTwo JOIN tableOne ON tableOneId = tableTwoId
GROUP BY
  tableOneId

所有提到的列都声明为numeric(30,6) NOT NULL

tableOne中,我的条目的总和(列a, b, c)应该等同于d中的列Table Two

一个简单的例子:

Table One (id here should read tableOneId to match above query)
  id=1, a=1, b=0, c=0
  id=1, a=0, b=2, c=0
  id=2, a=1, b=0, c=0

Table Two (id here should read tableTwoId to match above query)
  id=1, d=3
  id=2, d=1

我的第一次迭代使用了SUM(d)/COUNT(*),但是分区很乱,所以我目前正在使用MIN(d)。什么是更好的方式来编写这个查询?

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
  tableOneId,
  tableOneData,
  d AS tableTwoData
FROM tableTwo
JOIN (select tableOneId, sum(a + b + c) AS tableOneData
      from tableone
      group by 1) x ON tableOneId = tableTwoId
where tableOneData <> d;

这将返回表2中包含不正确数据的所有行。

答案 1 :(得分:1)

select tableOneId, SUM(a) + SUM(b) + SUM(c) as tableOneData, d as tableTwoData
from  tableTwo JOIN tableOne ON tableOneId = tableTwoId
GROUP BY tableOneId, d