sql - Find the most recent row of a group -
i know there no "last" row hope i'm clear isn't i'm looking for. want select rows in table if value of 1 particular field last alphabetically. i'll try best draw out below. i'm bit of novice please bear me...
table [order number], [delivery date], [order qty], [shipped qty], [bill to], [ship to], [invoice number]
there many times when reissue invoices , invoice number increment letter. update additional field values well. below typical set multiples invoices...
'987654', '2014-05-01 00:00:00', '100', '90', 'billtoxyz', 'shiptoxyz', '987654a' - new record - '987654', '2014-05-01 00:00:00', '-100', '-90', 'billtoxyz', 'shiptoxyz', '987654b' - new record - '987654', '2014-05-01 00:00:00', '100', '100', 'billtoxyz', 'shiptonewshiptolocation', '987654c' - new record - '987654', '2014-05-01 00:00:00', '10', '10', 'billtoxyz', '2ndnewshiptolocation', '987654d' - new record -
what need query above fields , bring [invoice number] last(alphabetically) (in case 987654d) have sum values of [order qty] , [shipped qty] of records regardless of [invoice number].
if can provide additional information please let me know. thank in advance.
it possible use row_number
function last row in group setting order by
descending , using filter row value 1. sum
, max
windowing other aggregate values.
with d ( select [order number] , [delivery date] , sum([order qty]) on (partition [order number]) [total order qty] , [total shipped qty] = sum([shipped qty]) on (partition [order number]) , [bill to] , [ship to] , [last invoice number] = max([invoice number]) on (partition [order number]) , id = row_number() on (partition [order number] order [invoice number] desc) table1 ) select [order number] , [delivery date] , [total order qty] , [total shipped qty] , [bill to] , [ship to] , [last invoice number] d id = 1
Comments
Post a Comment