简体   繁体   中英

Get a table with one row per id and multiple columns from a table with multiple rows for same id and calculate sum based on condition

This is my commissions table where some ids have two entries and others only one. If there is a reverse entry within 30 days from the original commission date the original commission should be reversed, but if the reverse entry is after 30 days it should be ignored.

lead_id commission_date commission
22940 01/03/2020 30
22940 30/03/2020 -30
22941 30/04/2020 30
22942 31/03/2020 60
22942 15/06/2020 -60

Therefore this is the final table I want to get to.

lead_id total commission
22940 0
22941 30
22942 60

The code I have written for the first part of the query, should produce jut one row for any lead_id storing both commission dates and commission amounts if present (some ids only have one entry and no reverse commission). Here is the code

WITH TAB_RN AS
(
      SELECT commissions.lead_id, commissions.commission_date, commissions.commission_amount, ROW_NUMBER() OVER (PARTITION BY commissions.lead_id, commissions.commission_date) AS RN
  FROM commissions
)
SELECT T1.lead_id, 
       T1.commission_date AS DATE1, T1.commission_amount AS amount1
       T2.commission_date AS DATE2, T2.commission_amount AS amount2
FROM TAB_RN T1
LEFT JOIN TAB_RN T2 ON T1.lead_id = T2.lead_id AND T1.commission_date = T2.commission_date AND T2.RN = 2
WHERE T1.RN = 1

it should produce this result

lead_id date 1 amount1 date 2 amount2
22940 01/03/2020 30 30/03/2020 -30
22941 30/04/2020 30
22942 31/03/2020 60 15/06/2020 -60

but instead I'm returned

lead_id date 1 amount1 date 2 amount2
22940 01/03/2020 30
22940 30/03/2020 -30
22941 30/04/2020 30
22942 31/03/2020 60
22942 15/06/2020 -60

I then want to calculate the difference between date 1 and 2 and if the difference is less than 30 days sum amount 1 and amount2, otherwise only amount1 should be counted.

Finally I want to join the table with the companies table on commissions.company = companies.id and filter by company x

Just break it down

Select for commissions

select lead_id, commission_date, commission
from commissions
where commission > 0

Then join this to valid returned commissions

select commissions.lead_id, commissions.commission_date, commissions.commission + ret.commission as commission_total
from commissions
join (
  -- returned commissions have negative value.
  select lead_id, commission_date, commission
  from commissions
   where commsion < 0
) ret on commissions.lead_id = ret.ldead_id
       and   commissions.commission= ret.commission * -1
       and datediff(day,ret.commission_date,comm commissions.commission_date) <=30
where commission > 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM