sql - Select top N from group records -
i need list frist record when price changed. using below example.
invoice table records (group customer price , sorted date)
index customer date price 01 may-01-2016 $12.00 02 may-11-2016 $12.00 03 may-21-2016 $13.00 04 may-22-2016 $13.00 05 may-23-2016 $13.00 06 may-24-2016 $13.00 07 jun-01-2016 $14.00 08 jun-11-2016 $14.00 09 jun-21-2016 $14.00 10 jun-25-2016 $14.00 11 b may-02-2016 $12.50 12 b may-12-2016 $12.50 13 b may-22-2016 $13.50 14 b may-24-2016 $13.80 15 b may-26-2016 $13.80 16 b may-28-2016 $13.80 17 b jun-02-2016 $14.60 18 b jun-12-2016 $14.60 19 b jun-22-2016 $14.60 20 b jun-26-2016 $14.60
i need first record when price changed. result be:
01 may-01-2016 $12.00 03 may-21-2016 $13.00 07 jun-01-2016 $14.00 11 b may-02-2016 $12.50 13 b may-22-2016 $13.50 14 b may-24-2016 $13.80 17 b jun-02-2016 $14.60
further query, can limited result latest 2 records each customer? result be:
03 may-21-2016 $13.00 07 jun-01-2016 $14.00 14 b may-24-2016 $13.80 17 b jun-02-2016 $14.60
thank you.
;with cte ( select * , cast(substring([date], 5,2) + '-' + left([date] , 3) + '-' + right([date] ,4) date) datedt invoice) ,cte2 ( select * ,row_number() on (partition price , customer order datedt asc) rn cte ) select [index] ,customer, [date] ,price cte2 rn = 1 order customer , datedt
result set
╔═══════╦══════════╦═════════════╦═══════╗ ║ index ║ customer ║ date ║ price ║ ╠═══════╬══════════╬═════════════╬═══════╣ ║ 01 ║ ║ may-01-2016 ║ 12.00 ║ ║ 03 ║ ║ may-21-2016 ║ 13.00 ║ ║ 07 ║ ║ jun-01-2016 ║ 14.00 ║ ║ 11 ║ b ║ may-02-2016 ║ 12.50 ║ ║ 13 ║ b ║ may-22-2016 ║ 13.50 ║ ║ 14 ║ b ║ may-24-2016 ║ 13.80 ║ ║ 17 ║ b ║ jun-02-2016 ║ 14.60 ║ ╚═══════╩══════════╩═════════════╩═══════╝
Comments
Post a Comment