首页 > 解决方案 > 使用 sum 和内部联接的查询不起作用

问题描述

我不知道为什么这个 SQL 查询不能正常工作,它返回相同的记录而不使用sum函数求和

select      *, sum(VenteProduit.MontantHT) as 'TOTAL HT' 
from        RegFacture 
inner join  VenteProduit 
        on  RegFacture.NumFacture = VenteProduit.NumFacture  
group by  VenteProduit.NumFacture, 
          RegFacture.NumFacture, 
          RegFacture.DateFacture, 
          RegFacture.ModePaiment, 
          RegFacture.DateEcheance, 
          RegFacture.TVA, 
          RegFacture.Devise, 
          RegFacture.MontantPayee,
          RegFacture.RestMontant,
          RegFacture.LieuLivraison,
          RegFacture.incoterm,
          RegFacture.Unite,
          VenteProduit.RsClient,
          VenteProduit.RefProduit,
          VenteProduit.PrixVente,
          VenteProduit.Quantitee,
          VenteProduit.MontantHT

它返回相同的记录结果应该是 2100

标签: sql-serversum

解决方案


使用窗口函数解决了问题

新的查询是:

select *,sum(VenteProduit.MontantHT) OVER(PARTITION BY VenteProduit.NumFacture) as 'TOTAL HT' 
FROM [dbo].VenteProduit 
inner join RegFacture on RegFacture.NumFacture=VenteProduit.NumFacture

推荐阅读