简体   繁体   中英

Sum of rows in SQL with GROUP BY

I am having a table with data like:

ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180

I want the output like:

ORDERID    TaxableValue       TaxValue
   5           3000               740

How can I achieve this? I tried with:

SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue 
FROM table1 
GROUP BY OrderId;

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

Pretty sure it is as simple as doing a little math.

select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from YourTable
group by OrderID

EDIT: The math was slightly off on the TaxableValue

For those who want proof that this works.

declare @Something table
(
    ID int
    , OrderId int
    , TAX int
    , Quantity int
    , UnitCost int
)

insert @Something values
(1, 5, 28, 2, 228)
, (2, 5, 18, 1, 118)

select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from @Something
group by OrderID

This is how it can be done.

SELECT 
orderid, 
sum(unitcost*quantity) - sum(tax*quantity) as taxablevalue,
sum(tax*quantity) as taxvalue
FROM table1  
GROUP BY OrderId;
select OrderId
    , SUM((unitcost * quantity * tax)/(100+tax)) as TaxValue
    , SUM(unitcost * quantity)-SUM((unitcost * quantity * tax)/(100+tax)) as taxableValue
from table1
group by OrderId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM