表1每个id有一行,表2每个id有1行,其中entrytype = 0,而每个id有多行,其中entrytype = 1。
我运行以下查询:
SELECT sum(amount) FROM table1 where id = 'AUS|License|Maintenance|Aug_2016'
select sum(amount) from table2 where entrytype = 0 and id = 'AUS|License|Maintenance|Aug_2016'
select sum(amount) from table2 where entrytype = 1 and id = 'AUS|License|Maintenance|Aug_2016'
并获得以下结果:
7689.12
7689.12
7689.119999
现在,我想在两个表的sum(amount)
中搜索表1 sum(amount) <> table2 sum(amount)
的特定ID的情况
答案 0 :(得分:0)
如果您想要一个特定的ID,可以使用cross join
将它们组合在一起:
select t1.amount, t2_0.amount, t2_1.amount
from (SELECT sum(amount) as amount FROM table1 where id = 'AUS|License|Maintenance|Aug_2016'
) t1 cross join
(select sum(amount) as amount from table2 where entrytype = 0 and id = 'AUS|License|Maintenance|Aug_2016'
) t2_0 cross join
(select sum(amount) as amount from table2 where entrytype = 1 and id = 'AUS|License|Maintenance|Aug_2016'
) t2_1;
答案 1 :(得分:0)
如果我正确理解了您的要求,则可以将每个查询都放在它们共同的id
字段上,然后只需选择三个范围之和不相等的id
值子查询,例如:
SELECT a.id, a.s1, b.s2, c.s3
FROM
(
(
SELECT id, SUM(amount) AS s1
FROM table1
GROUP BY id
) a
INNER JOIN
(
SELECT id, SUM(amount) AS s2
FROM table2
WHERE entrytype = 0
GROUP BY id
) b ON a.id = b.id
)
INNER JOIN
(
SELECT id, SUM(amount) AS s3
FROM table2
WHERE entrytype = 1
GROUP BY id
) c ON a.id = c.id
WHERE NOT (a.s1 = b.s2 AND a.s1 = c.s3)
您未指定DBMS,所以为了防万一,我在其中加入了MS Access所需的额外括号。
通过使用INNER JOINs
,我还假设您只对所有三个子查询中都存在的记录感兴趣;如果子查询之一是主查询,则使用LEFT JOINs
加入其他两个子查询,以便返回主数据库中的所有记录。
包括后续注释中提到的另外两列-
SELECT a.id, a.s1, b.s2, c.s3, a.s1 - b.s2 AS s4, a.s1 - c.s3 AS s5
FROM
(
(
SELECT id, SUM(amount) AS s1
FROM table1
GROUP BY id
) a
INNER JOIN
(
SELECT id, SUM(amount) AS s2
FROM table2
WHERE entrytype = 0
GROUP BY id
) b ON a.id = b.id
)
INNER JOIN
(
SELECT id, SUM(amount) AS s3
FROM table2
WHERE entrytype = 1
GROUP BY id
) c ON a.id = c.id
WHERE NOT (a.s1 = b.s2 AND a.s1 = c.s3)