简体   繁体   中英

Transact-SQL query subtotal column

When my sql query returns the results it looks like this:

Driver    Amount
A         $120.00
A          -$5.00
A          $10.00
B          $90.00

But now I've been requested to add a column to the query results that will present the total for each driver. So it should now look like this:

Driver          Amount       Subtotal
A              $120.00        $125.00
A               -$5.00        $125.00
A               $10.00        $125.00
B               $90.00         $90.00

Possible?

Use window functions.

with cte as (
      <your query here>
     )
select cte.*,
       sum(amount) over (partition by driver) as subtotal
from cte;

You can probably incorporate this logic directly into the query that returns the first results as well.

Sorry that I can't provide you with the full query, but the following link may help accomplish what you need with GROUP BY and ROLLUP, if you're using MS SQL.

https://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx

one other way of doing this would be to use CTE (Common Table Expression)

With cteName as (
    Select DriverId,
    Sum(DriverAmount) As TotalDriverAmount
    FROM YourTable
    GROUP BY DriverId
),
Select YourTable.DriverId, DriverAmount, cteName.TotalDriverAmount
FROM YourTable LEFT JOIN cteName ON(cteName.DriverId = YourTable.DriverId)
SELECT T.DRIVER, T.AMOUNT, S.TOT [SUBTOTAL] FROM YOURTABLE T JOIN 
(SELECT DRIVER, SUM(AMOUNT) TOT FROM YOURTABLE GROUP BY DRIVER ) S 
ON T.DRIVER = S.DRIVER

This should work on just about any MS-SQL version.

From https://www.sqlservercentral.com/Forums/Topic1541134-3412-1.aspx

This is really easy thanks to some (Windowing) functionality born in 2005.

SELECT  OrderNo
        ,Something
        ,Amount
        ,SubTotal = SUM(Amount) OVER (PARTITION BY OrderNo)    
FROM #TestTable   
ORDER BY OrderNo, Something

Create a function that get driver Id, query driver data and return total, call that function in query

Select DriverId, Amount, func(driverId) as TotalAmount
FROM Table

    function func(ID){
   return(Select sum(amount) from table where driverid=ID);
    }

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