RowNumber() and SUM() in one query
12,606
you can also do sum(field) over (...)
select
row_number() over (partition by ca.logical_number order by t.timestamp DESC) as rownumber,
sum(amount_transfered) over (partition by ca.logical_number ) as total_amount_transfered
from ...
Author by
Admin
Updated on June 20, 2022Comments
-
Admin about 2 years
is there some way who to get last record using rownumber() and SUM of one field (money in this case)? I've tried to come up with a query like:
SELECT [date] ,... FROM ( SELECT CAST(t.timestamp AS DATE) AS [date] ,.../some fields/ ,row_number() over (partition by ca.logical_number order by t.timestamp DESC) as rownumber --last update(record) transaction --,amount_transferred = --( -- SELECT -- ,SUM(t.money_value) AS amount_transferred -- FROM -- TO_Transaction t -- GROUP BY -- CAST(t.timestamp AS Date) --) ) AS t WHERE rownumber=1
What the query is supposed to do is to find current purse balance and all money transferred during a day. Any help would be aprreciated. Thanks.
-
Jamiec about 7 yearsThanks @Gordon - order by makes no sense in a sum.
-
Admin about 7 yearsMy godness, it probably works! :-) Will mark as right answer when the time needed before expires.
-
Jamiec about 7 years@StanislavJirák shocking!
-
Admin about 7 yearsI'm new to SQL and after some time spent, I was going to split the procedure into 2 pieces.
-
Jamiec about 7 yearsI'm old to sql and the day i realised i could add an
over()
to any aggregate function was a good day! -
Admin about 7 yearsYes, it seems over() is quite handy. This is good day fro me!