Reputation: 363
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?
Upvotes: 0
Views: 241
Reputation: 221
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
Upvotes: 0
Reputation: 2800
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);
}
Upvotes: -2
Reputation: 4014
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.
Upvotes: 0
Reputation: 1269633
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.
Upvotes: 3
Reputation: 238
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)
Upvotes: 0