Financial time series calculations are rarely simple SQL queries. Three kinds are common: splitting an account’s transaction records into sessions based on the time gap between them; filling in the prices missing on days a stock is halted; and finding the longest run of consecutive gains in a series of closing prices. In SQL, all three have one thing in common: they produce intermediate states along the way, such as session groups, the source of each filled value, and interval numbers, and these intermediate columns never appear in the final result set.
There must be a place to store the intermediate states. The common approach is to write a stored procedure or create temporary tables, save the intermediate results there, and process them step by step. There’s nothing wrong with this approach, except that the intermediate states end up locked inside the procedure: change one condition and you have to re-read the whole procedure, and you can’t stop at an intermediate step to check the result.…