multiply and SUM() MS SQL

2019-09-21 19:37发布

问题:

I'm trying to do multiply two columns and SUM() all rows in a SQL SELECT but I can't get the right value. I think it is becouse of the negative values in the columns.

So were it is negative value in Antalpallar like this -1200 *-2 should be -2400 but i don't think it's doing that, or? It is stuff going in and out of a warehouse.

Anyhow, the final value of adding those togheter should be 14320, but i get one on 20 000 something and without ABS()(or with) a sum on 5000 something.

Anyone knows how to write this SUM(e.Antalperpall * ABS(e.Antalpallar)) to get the value i want? obviously there are something i've missed.

SELECT a.Artikelnummer
    ,a.Artikelnamn
    ,a.Antalperpall
    ,COUNT(*) AS AntalArtiklar
    ,SUM(e.Antalpallar) AS TotalPall
    ,SUM(e.Antalperpall * ABS(e.Antalpallar)) AS TotalStyck
FROM Artikel AS a
INNER JOIN Evig AS e ON a.ArtikelnummerID = e.ArtikelnummerID
WHERE (e.Datum <= '{0}')
    AND (a.Kundkund = '{1}')
    AND (a.Artikelnamn = '{2}')
GROUP BY a.Artikelnummer
    ,a.Artikelnamn
    ,a.Antalperpall

回答1:

@fia Maybe you should do your calculation elsewhere first for example on paper or in Excel to ensure you know exactly what you should get. It would also help you figure out the order of the calculation before writing it in SQL. According to the figures shown the values you've stated seems to be correct i.e 22,720 for multiply then sum the figures as is, or 5,920 if you use the Absolute value of the second column. If both columns use absolute values then it will also give 22,720. If you're sure you need to get 14,320 then you may need to get clarification of the calculation needed or revise that number.

Additionally, your values may be wrong. You can get 14, 320 if the values for the 2nd and 3rd rows in the second column was -1 and 1 respectively.