select a.sec_no, a.amount, min(price_date) as FirstDateAtPrice, No_of_days_at_price = COALESCE(DATEDIFF(d, c.price_date, a.price_date),0) from ( select *, ROW_NUMBER() over (partition by sec_no order by price_date desc) rn from @sec_temp) a outer apply ( select top 1 * from @sec_temp b where a.sec_no=b.sec_no and a.amount <> b.amount order by b.price_date desc ) c where a.rn=1
In subquery A, the largest-1-per-group is issued, that is, the most recent price record for each sec_no. Subquery C finds the first previous record that has a different price for the same sec_no. The difference in the two dates is the search for number of days . If you want it to be no previous date, change the end of the line COALESCE to 1 instead of 0.
EDITED to clarify the issue
To start counting from the first date equal to the current bid, use this query instead
select sec_no, amount, No_of_days_at_price = 1 + DATEDIFF(d, min(price_date), max(price_date)) from ( select *, ROW_NUMBER() over (partition by sec_no order by price_date desc) rn, ROW_NUMBER() over (partition by sec_no, amount order by price_date desc) rn2 from @sec_temp ) X WHERE rn=rn2 group by sec_no, amount
AND FINALLY If the required result is actually days between
- The first date when the price is equal to the current; and
- Today
Then the only part that needs to be changed is this:
No_of_days_at_price = 1 + DATEDIFF(d, min(price_date), getdate())