2

我有以下查询:

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)应等于 中的dTable 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). 编写此查询的更好方法是什么?

4

2 回答 2

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 中所有数据不正确的行。

于 2012-07-20T00:46:59.697 回答
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
于 2012-07-20T00:40:02.190 回答