I have a query which has 2 levels to it, Matter level which is the highest level and Claimant level where there could be multiple to one Matter level (there is only ever one Matter level)
Here is a generic example
create table #tmp1 ( Matter_Key INT NOT NULL ,Matter_Number INT NOT NULL ,Matter_Description Varchar(30) NOT NULL ) Create Table #tmp2 ( Matter_Key INT NOT NULL ,Claimant_Key INT NOT NULL ,Claimant_Name Varchar(30) NULL ,Descript Varchar(30) NULL ,Amount Decimal(17,2) ,Amount2 Decimal(17,2) ) INSERT INTO #tmp1 VALUES ('1','1234','Law Vs Company') INSERT INTO #tmp1 VALUES ('2','2345','Toon Vs Company') INSERT INTO #tmp2 VALUES ('1','1','Rob','Judgement',12.45,7.25) INSERT INTO #tmp2 VALUES ('1','2','Mark','Other',300.00,50.00) INSERT INTO #tmp2 VALUES ('1','3','Joel','Judgement',150.00,NULL) INSERT INTO #tmp2 VALUES ('2','4','Hayley','Judgement',Null,15.00) INSERT INTO #tmp2 VALUES ('2','5','Sofia','Report',75.00,NULL) Select mr.Matter_Number ,mr.Matter_Description ,Coalesce(CLA.CLAAmount,0) as Amount1 ,Coalesce(CLA.CLAAmount2,0) as Amount2 from #tmp1 as mr LEFT JOIN ( Select Matter_Key ,Claimant_Name ,SUM(Amount) as CLAAMOUNT ,SUM(Amount2) as CLAAMOUNT2 From #tmp2 Group BY Matter_Key ,Claimant_Name ,Descript )CLA on mr.Matter_Key=CLA.Matter_Key DROP TABLE #tmp1 DROP TABLE #tmp2
But I only want to see the value of Amount and Amount2 where Descript is Judgement but still see the same number of rows as the first query
So I used the following
Select mr.Matter_Number ,mr.Matter_Description ,Coalesce(CLA.CLAAmount,0) as Amount1 ,Coalesce(CLA.CLAAmount2,0) as Amount2 from #tmp1 as mr LEFT JOIN ( Select Matter_Key ,Claimant_Name ,SUM(Amount) as CLAAMOUNT ,SUM(Amount2) as CLAAMOUNT2 From #tmp2 WHERE Descript = 'Judgement' Group BY Matter_Key ,Claimant_Name ,Descript )CLA on mr.Matter_Key=CLA.Matter_Key
But this pretty much turns the left join into a inner join.
I have come up with the following to resolve it
Select mr.Matter_Number ,mr.Matter_Description ,Coalesce(CLA.CLAAmount,0) as Amount1 ,Coalesce(CLA.CLAAmount2,0) as Amount2 from #tmp1 as mr LEFT JOIN ( Select Matter_Key ,Claimant_Name ,CASE WHEN Descript = 'Judgement' THEN SUM(Amount) ELSE NULL END as CLAAMOUNT ,CASE WHEN Descript = 'Judgement' THEN SUM(Amount2) ELSE NULL END as CLAAMOUNT2 From #tmp2 Group BY Matter_Key ,Claimant_Name ,Descript )CLA on mr.Matter_Key=CLA.Matter_Key
There are quite a few columns from #tmp2 that I need to sum like this so is there a better way to do it.
Regards