在SQL上对3个表使用联接时出现问题
我有三个问题在SQL上对3个表使用联接时出现问题,sql,select,join,Sql,Select,Join,我有三个问题 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_
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.ug=tab_ug.cod
连接到“contas”表格。
表格“justicativas”通过contas.cod=justicativas.cod\u contas
连接到“contas”表格
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
我认为你可以这样做:
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
第一步(使用表格别名,使其更清晰):
(在连接表时始终使用ON
子句)
此查询假定您只希望检索所有表中存在的项。如果在contas
中未找到选项卡ug
中的给定项目,则该项目将不包括在
结果集。类似地,如果在contas
中未找到justificativas
中的给定项“found”,则不会将其分解到结果集中。工作
围绕这一点,您需要使用外部联接,如下所示:
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
中没有匹配项;类似地,contas
中的所有项目都将被考虑在内,即使它们有
justicativas
中没有项目
这里有一个更微妙的问题:如果给定的contas
项在justicativas
中有两行或更多相关行,那么contas
项将被分解
多次计入总和,例如
ug contas justificativas
1 A, 1 j7, 102
1 A, 1 j8, 103
2 <null> <null>
在这一点上,我不得不放弃,因为我不知道查询要求的全部范围。这不是我想要的,where子句不能在一起,它过滤查询的次数超过了它应该过滤的次数。。。我需要使用完全连接,但它不起作用。我遇到了一个错误:“FROM关键字not found where expected”,这通常意味着您在select语句中指定的最后一个字段后面有一个额外的逗号……有吗?我在错误的位置没有看到逗号,我使用的代码与您发布的代码完全相同(除了tag_ug,即tab_ug:P)是[]阻止了查询,我使用了“”,它起了作用,但这并不完全是我想要的,它返回的结果与从Fabien解决方案中选择的结果相同
ug contas justificativas
1 A, 1 j7, 102
1 A, 1 j8, 103
2 <null> <null>
cod FirstSum SecondSum
1 2 205
2 0 0