Sqlserver
 SQL >> Base de Dados >  >> RDS >> Sqlserver

Evitar somas incorretas após juntar segunda tabela

Se o join multiplica linhas e distorce a soma, calcule o agregado antes de juntar ou use função de janela.

WITH R AS (SELECT *, SUM(HeadCount) OVER (PARTITION BY date) AS SumHeadCount FROM Report)
SELECT R.date, SumHeadCount, SUM(P.Quantity) AS SumQuantity
FROM R JOIN Production P ON R.ReportID = P.ReportID
GROUP BY R.date, SumHeadCount
ORDER BY R.date;