vendredi 11 septembre 2015

SQL - How To Group Data Following Individual Row Calculations

I'm fascinated by this problem. Here's a stripped down version of my full sqlite query:

SELECT OrderID,
       UnitPrice,
       Quantity,
       Discount
FROM Order Details;

Which returns this:

OrderID  UnitPrice  Quantity  Discount
10248    14.0       12        0.00
10248    9.8        10        0.00
10248    34.8        5        0.00
10249    18.6        9        0.00
10249    42.4       40        0.00
10250    7.7        10        0.00
10250    42.4       35        0.15
10250    16.8       15        0.15
10251    16.8       6         0.05
10251    15.6       15        0.05

I want to return a new column called total price. This would be a calculation of UnitPrice multiplied by Quantity less the corresponding percentage Discount. The complication arises however in that the new column should be grouped by the OrderID to represent the total order price less the individual % discounts.

I've been chasing my tails with SUM aggregates and GROUP BY's for hours trying to solve this! Summing the UnitPrices and Quantities is fine. But as the discount applies to different values, it's almost like it needs to be calculated first somehow. The discount does not need to apply individually to each item, btw.

Aucun commentaire:

Enregistrer un commentaire