'SQL Count and Group by derived logic (Db2)

This code works. However, I want to run it without the filter for contract_No and then it doesn't work:-(. I'm sure im missing a left join and some steps.

Basically I have Contracts and contract lines (same table - Contract_repo), and I want to create a grouping of contract lines based on how many payments they have had last 12 months (different table on another level - Payments - and then count contract lines per group and rolled up to contract_No level.

Select a.Contract_No,count (*) as "Active Contract Lines",
(select count(distinct b.Contract_Line_No)
 from Payments b
 where b.Contract_NO = 32778
 and b.Contract_Line_No=(
  select distinct 
   case when Count(
    Case when  MONTHS_BETWEEN((CURRENT DATE - 1 MONTH),c.Period) < 11 
    then 1 end
    )=0 
    then c.Contract_Line_No end
   )  
  from  Payments c 
  where c.Contract_No = b.Contract_No
  group by c.Contract_Line_No
 ) as "Contract_Line = 0 trx L12M"
from Contract_Repo a
where a.Contract_NO =  32778
and a.status = 1
group by a.Contract_NO

This is my desired output:

Contract_No Active Lines Lines with zero trx Lines with 12 trx
12345 1000 600 400
67894 100 10 90
101112 500 100 400


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source