0

我有这三个表:

  • 账户:id(pk)、value、ug(fk)、flag
  • 证明:id(pk),值,account_id(fk)
  • 客户端:id(pk), ug(fk)

我有这两个选择:

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

但我找不到办法;有任何想法吗?

4

2 回答 2

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
于 2013-07-26T19:36:44.427 回答
0

我们真的不应该对你的问题做任何猜测,但似乎猜测是必要的。

我认为你的三张桌子是:

  1. Account — id (PK), value, ug (FK 引用 Client), flag
  2. 客户——ug (PK)
  3. Justify — value, account_id (PK, 也 FK 引用 Account)

我假设没有客户就没有帐户,没有帐户就没有理由条目(因此 PK 和 FK 约束都由 DBMS 强制执行)。这意味着不必从客户端表中进行选择。

如果您希望客户不一定也列出任何帐户,您可能最好使用单独的查询,但如果有必要可以这样做 - 您必须澄清您的问题,并使用额外级别的外部连接,并担心空值与零值等。

看来所需的输出是:

  • 对于每个客户,列出客户标识符ug(尚不清楚每个帐户的 Justify 表中是否总是存在值。

但是,我们可以尝试通过逐步构建查询来提供信息。

为特定用户汇总帐户值

SELECT a.ug, SUM(a.value) AS ac_value
  FROM Account AS a
 WHERE a.flag = 1
 GROUP BY a.ug

为特定用户聚合 Justify 的值

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 也是其中的一部分。

于 2013-07-26T19:39:56.443 回答