At work, one of my tasks is to calculate the commission for sales staff. One rule was more complex than the other.
The two sales teams A and B work together to sell different products. Team A can send commands to team B. The same client can send several times. The first time a client (for example, 1st lead) * sends a commission, it is paid to the seller in team A, which created the leading position. Now the client is "blocked" for the next 365 days (from the date of creation of date 1). This means that no one can get additional commission for this client during this period by sending additional leaders (for example, Lead 2 and 3 does not receive commissions). After 365 days. A new guide can be created and receive a commission (for example, guide 4). Then the client is again blocked for 365 days, counting from the day that output 4 was created. Therefore, management 5 does not receive a commission. The tricky part is resetting the date for 365 days.
'* Link to tables #LEADS and #DISERED.
I solved the problem in tSQL with a cursor, but I am wondering if recursive CTE can be used instead. I made several attempts which are best inserted below. The problem with my solution is that I refer to the recursive table more than once. I tried to fix this problem with embedding CTE inside CTE. That is not allowed. I tried using a temporary table inside the CTE, which is also not allowed. I tried several times to recode the recursive part of the CTE, so that the recursive table refers only once, but then I can not get the logic to work.
I am using SQL 2008
IF OBJECT_ID('tempdb.dbo.#LEADS', 'U') IS NOT NULL DROP TABLE
source share