如何加入3张或更多桌子

时间:2019-07-05 09:34:02

标签: sql-server

我有3张桌子:

--------------------------------------------
DISPO,       ARTICLE,         SALES
--------------------------------------------
GQ_ARTICLE,  GA_ARTICLE,      GL_CODEARTICLE
GQ_PHISIQUE, GA_CODEARTICLE,  GL_QTEFACT
--------------------------------------------

DISPO&ARTICLE通过:链接

DISPO.GQ_ARTICLE = ARTICLE.GA_ARTICLE 

文章和销售链接:

ARTICLE.GA_CODEARTICLE = SALES.GL_CODEARTICLE

我想显示:

ARTICLE.GA_ARTICLE, SUM(GQ_PHISIQUE), SUM(SALES.GL_QTEFACT)

我已经尝试过,查询已执行但没有结果(超过10分钟没有结果)

SELECT ARTICLE.GA_ARTICLE, SUM(GQ_PHYSIQUE), SUM(SALES.GL_QTEFACT)

FROM DISPO
INNER JOIN ARTICLE ON DISPO.GQ_ARTICLE = ARTICLE.GA_ARTICLE
INNER JOIN SALES ON ARTICLE.GA_CODEARTICLE = SALES.GL_CODEARTICLE

GROUP BY ARTICLE.GA_ARTICLE

1 个答案:

答案 0 :(得分:0)

查询不起作用的原因是3个表的直接联接返回重复的行,这些行将总和相乘。
将第一个表与其他两个表分别连接起来,然后将结果连接到第一个表:

select 
  a.article
  d.totalphysique
  s.totalqtefact
from article a 
left join (
  select 
    a.ga_article,
    sum(d.gq_physique) totalphysique
  from article a inner join dispo d
  on d.gq_article = a.ga_article
  group by a.ga_article
) d on d.ga_article = a.ga_article
left join (
  select 
    a.ga_article,
    sum(s.gl_qtefact) totalqtefact
  from article a inner join sales s
  on s.gl_codearticle = a.ga_article
  group by a.ga_article 
) s on s.ga_article = a.ga_article