Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Somma errata quando mi unisco a un secondo tavolo

Un modo per evitarlo (soggetto al supporto RDBMS) sarebbe

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