Sql server 总和和内部联接不起作用的查询
我不知道为什么这个SQL查询不能正常工作,它返回相同的记录而不使用Sql server 总和和内部联接不起作用的查询,sql-server,sum,Sql Server,Sum,我不知道为什么这个SQL查询不能正常工作,它返回相同的记录而不使用sum函数求和 select *, sum(VenteProduit.MontantHT) as 'TOTAL HT' from RegFacture inner join VenteProduit on RegFacture.NumFacture = VenteProduit.NumFacture group by VenteProduit.NumFacture,
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
使用窗口功能解决问题 新查询是:
select *,sum(VenteProduit.MontantHT) OVER(PARTITION BY VenteProduit.NumFacture) as 'TOTAL HT'
FROM [dbo].VenteProduit
inner join RegFacture on RegFacture.NumFacture=VenteProduit.NumFacture
您可以按
选择中的每一列对进行分组。从select
和groupby
1)中删除除MontantHT
之外的所有其他列。我强烈建议您在查询中学习使用别名,它们将使查询更具可读性。2) 您似乎是按查询中的每一列进行分组,因此您将获得每一行的结果,而不进行聚合,因此也不进行求和。在SQL Server中,不能同时选择所有列和聚合。如果您希望这样做,您需要一个窗口函数。@Mohamed-为什么要撤消我应用于您的查询的格式?现在无法读取?很抱歉,我修改了代码,因为我想在内部联接模式下显示表的所有列,但是Sum()函数不适用于每个NumfactureI。我已经为您设置了查询的格式。请参考,添加空格
以分隔列名,使其更具可读性,并且不会影响查询性能