我有这三张桌子:
我有两个选择:
select sum(account.value)
from account, client
where client.ug_id = account.ug and flag = 1
select sum(justify.value)
from justify, client, account
where client.ug_id = account.ug
and flag = 1 and justify.account_id = account.id
我正在尝试将它们放在一个查询中,如下所示:
select
1,
1-2,
account.ug
from account
group by account.ug
但我找不到办法去做;任何想法?
答案 0 :(得分:0)
您还没有真正告诉我们您的架构。但是(抓住东西)......
首先,您应该使用ANSI / ISO连接,而不是旧式连接。 ANSI / ISO连接更容易阅读。执行此操作后,您将需要使用派生表,它们是from
子句中充当虚拟视图的子查询。那么,这样的事情应该对你有用:
select ug = account.ug , -- guaranteed to be present ,
total = coalesce( total.value , 0 ) ,
delta = coalesce( total.value , 0 ) ,
- coalesce( justify.value , 0 )
from ( select distinct -- we do select distinct here
ug -- to guarantee at least one row for every UG
from account -- some account UGs might be missing client rows
) account -- and/or some might be missing justify rows.
left join ( select ug = account.ug ,
value = sum(account.value)
from account
join client on client.ug_id = account.ug
where flag = 1
group by account.ug
) total on total.ug = account.ug
left join ( select ug = account.ug ,
value = sum(justify.value)
from account
join justify on justify.account_id = account.id
join client on client.ug_id = account.ug
where flag = 1
group by account.ug
) justify on justify.ug = account.ug
答案 1 :(得分:0)
我们真的不应该对你的问题做任何猜测,但似乎猜测是必要的。
我认为你的三张桌子是:
我假设没有客户端没有账户,没有账户没有合理的条目(所以PK和FK约束都是由DBMS强制执行的)。这意味着无需从Client表中进行选择。
如果您想要的客户也不一定列出任何帐户,您可能最好使用单独的查询,但如果需要可以这样做 - 您必须澄清您的问题,并使用额外的级别外联接,并担心空值与零等。
似乎所需的输出是:
ug
),帐户表(account.value)中帐户值的总和,以及帐户的值减去值的总和在Justify表中。目前尚不清楚每个帐户的Justify表中是否总会有值。但是,我们可以通过逐个构建查询来尝试提供信息。
SELECT a.ug, SUM(a.value) AS ac_value
FROM Account AS a
WHERE a.flag = 1
GROUP BY a.ug
SELECT a.ug, SUM(j.value) AS ju_value
FROM Account AS a
JOIN Justify AS j ON j.account_id = a.id
WHERE a.flag = 1
GROUP BY a.ug
SELECT b.ug, b.ac_value, b.ac_value - NVL(d.ju_value, 0) AS delta
FROM (SELECT a.ug, SUM(a.value) AS ac_value
FROM Account AS a
WHERE a.flag = 1
GROUP BY a.ug
) AS b
LEFT JOIN
(SELECT a.ug, SUM(j.value) AS ju_value
FROM Account AS a
JOIN Justify AS j ON j.account_id = a.id
WHERE a.flag = 1
GROUP BY a.ug
) AS d ON b.ug = d.ug
使用NVL允许Justify表中没有条目的客户端; LEFT JOIN也是其中的一部分。