0

我有这 3 个查询

select tab_ug.cod 
  from tab_ug

select coalesce(sum(valor),0)
  from contas
 where contas.conta_monitorada = 'Sim'
group by ug

select coalesce(sum(valor_justificativa),0)
  from contas, justificativas
 where contas.cod = justificativas.cod_contas
   and contas.conta_monitorada = 'Sim'
group by ug

我想将它们加入一个查询中,但我在这样做时遇到了麻烦......有人可以帮忙吗?表“ tab_ug ”通过 连接到“ contas ”表contas.ug = tab_ug.cod。表“ justificativas ”通过以下方式连接到“ contas ”表contas.cod = justificativas.cod_contas

4

3 回答 3

1

尝试这个:

select  t.cod,
        coalesce(sum(c.valor), 0) As [ValorSum],
        coalesce(sum(j.valor_justificativa), 0) As [ValorJustSum]
from tag_ug t
inner join contas c On c.ug = t.cod
inner join justificativas j On j.cod_contas = c.cod
where c.conta_monitorada = 'Sim'
group by t.cod,
        c.ug
于 2013-07-31T15:21:52.467 回答
0

第一遍(使用表别名,使其更清晰):

SELECT
   t1.cod
  ,coalesce(sum(t2.valor), 0)  FirstSum
  ,coalesce(sum(t3.valor_justificativa), 0)  SecondSum
 from tab_ug t1
  inner join contas t2
   on co.ug = t1.cod
  inner join justificativas t3
   on t3.cod_contas = t2.cod
 where t2.conta_monitorada = 'Sim'
 group by t1.cod

(连接表时始终使用该ON子句)

此查询假定您只想检索所有表中存在的项目。如果在tab_ug中找不到给定的项目,则不contas会将其包含在结果集中。同样,如果在contas中未找到“找到”的给定项目justificativas,则它不会被考虑到结果集中。要解决此问题,您需要使用外部连接,如下所示:

SELECT
   t1.cod
  ,coalesce(sum(t2.valor), 0)  FirstSum
  ,coalesce(sum(t3.valor_justificativa), 0)  SecondSum
 from tab_ug t1
  left outer join contas t2
   on co.ug = t1.cod
    and t2.conta_monitorada = 'Sim'
  left outer join justificativas t3
   on t3.cod_contas = t2.cod
 group by t1.cod

ON(如果没有该子句,外连接很难正常工作......)

这将包括所有项目,tab_ug即使它们在contas;中没有匹配项。同样,所有项目 incontas都将被考虑在内,即使它们在 中没有项目justificativas

这里有一个更微妙的问题:如果给定的contas项目在 中有两个或更多相关行justificativas,则该contas项目将多次计入总和,例如

ug   contas   justificativas
1     A, 1         j7, 102
1     A, 1         j8, 103
2     <null>       <null>

group by 将拿下这个并制作

cod  FirstSum   SecondSum
1       2           205
2       0             0

在这一点上我不得不放弃,因为我不知道查询要求的全部范围。

于 2013-07-31T15:34:22.167 回答
0

我认为你可以这样做:

select contas.ug, coalesce(sum(valor),0), coalesce(sum(valor_justificativa),0)
  from tab_ug, contas, justificativas
 where contas.conta_monitorada = 'Sim'
   and contas.ug = tab_ug.cod
   and contas.cod = justificativas.cod_contas
 group by contas.ug
于 2013-07-31T15:22:04.990 回答