我有2个查询:第一个显示库存,第二个显示销售。
--STOCK DEPOT
SELECT GQ_ARTICLE AS 'CODE ARTICLE',
SUM (GQ_PHYSIQUE)
FROM DISPO
GROUP BY GQ_ARTICLE
--SALES IN 6 MONTHS
--UNION ALL
SELECT GL_CODEARTICLE AS 'CODE ARTICLE',
SUM(GL_QTEFACT)AS 'SOLD QUANTITY'
FROM GCLIGNEARTDIM
WHERE
DATEADD(M, 6, GP_DATEPIECE) > getdate()
GROUP BY GL_CODEARTICLE
我尝试了UNIION ALL在两个查询之间进行组合,但是执行时间很长。即使我只花1天。
有什么解决方法吗?
我想要这样的结果:
GQ_ARTICLE SUM (GQ_PHYSIQUE) SUM (GQ_PHYSIQUE)
xxxx 24 50
答案 0 :(得分:2)
两个完全不相关的表之间的联合:
select
FirstName as Column1,
LastName as Column2,
email as Column3,
null as Column4
from
stock
union
select
ProductName as Column1,
QuantityPerUnit as Column2,
null as Column3,
UnitsInStock as Column4
from
product
答案 1 :(得分:0)
您似乎想要full join
而不是union all
,因为您希望将结果放在单行中:
SELECT COALESCE(l.CODE_ARTICLE, d.CODE_ARTICLE) as CODE_ARTICLE,
d.SUM_PHYSIQUE, l.SOLD_QUANTITY
FROM (SELECT GQ_ARTICLE AS CODE_ARTICLE, SUM(GQ_PHYSIQUE) as SUM_PHYSIQUE
FROM DISPO
GROUP BY GQ_ARTICLE
) d FULL JOIN
(SELECT GL_CODEARTICLE AS CODE_ARTICLE, SUM(GL_QTEFACT) AS SOLD_QUANTITY
FROM GCLIGNEARTDIM
WHERE GP_DATEPIECE > DATEADD(month, -6, getdate())
GROUP BY GL_CODEARTICLE
) l
ON l.CODE_ARTICLE = d.CODE_ARTICLE;
请注意第二个查询中对WHERE
条件的更改。如果合适的话,这将允许查询利用索引和分区。
答案 2 :(得分:0)
如果GQ_ARTICLE和GL_CODEARTICLE列引用相同的内容,那么您可以简单地联接表并使用case语句。 例如
SELECT GQ_ARTICLE AS 'CODE ARTICLE',
SUM (GQ_PHYSIQUE),
SUM(CASE WHEN DATEADD(M, 6, GP_DATEPIECE) > getdate() THEN GL_QTEFACT ELSE 0 END)
FROM DISPO
JOIN GCLIGNEARTDIM
ON GQ_ARTICLE=GL_CODEARTICLE
GROUP BY GQ_ARTICLE
编辑-根据您的数据,您可能需要向左/向右/全部外部连接此处...尽管易于更改...