Hope the below information will help you to understand the code
step1:
select distinct ACC_NO, PRODUCT, ACC_PLUS_PRODUCT, category,case when category='B' then 1 else 2 end as ord from have
group by ACC_NO, PRODUCT, ACC_PLUS_PRODUCT,category
The above code will select the distinct records based on ACC_NO, PRODUCT, ACC_PLUS_PRODUCT, category variables with a new variable
ord where it assigns 1 for category B and 2 for category S
Step2: using the data from step1 code will sum teh ord variable on ACC_NO, PRODUCT, ACC_PLUS_PRODUCT. By this we get
value 3 for those records which have category B and S and 1 for those records which have category B alone
select distinct ACC_NO, PRODUCT, ACC_PLUS_PRODUCT, sum(ord) as sum
step3:
We merge by left join the above code with sum variable with original dataset so that the original dataset will get the sum variable.
the merging happens by a.ACC_NO=b.ACC_NO and a.PRODUCT=b.PRODUCT and a.ACC_PLUS_PRODUCT=b.ACC_PLUS_PRODUCT. we again derive a new
sumamt2 variable from amt variable by case when sum>1 then sum(amt) else amt end as sumamt2, where if the sum value is 1 then amt values will be retained
and if sum value is not 1 then the amt values are summed into sumamt2 variable and this happens on group by variable
a.ACC_NO, a.PRODUCT, a.ACC_PLUS_PRODUCT and the having min(sort)=sort is to get the unique records on these records.
... View more