Question

select G.region as Region
    ,A.Name as AgencyName 
    ,A.AgencyId
    ,sum(L.LoanAmount) as LoanAmount
from dw.FFLoan L
inner join dw.dimborrower B on L.BorrowerId = B.BorrowerId 
inner join dw.DIMGeography G on G.GeographyId = B.GeographyId
inner join dw.DIMAgency A on A.AgencyId = L.Agency
group by G.region, A.Name, A.AgencyId
order by  Region, LoanAmount desc

i am not able to get output in like i first want first 5 east then 5 north and then south and then west. i need output only 5 region of each top loan amount

thank you

Was it helpful?

Solution 2

Try this,

;With CTE as
(
select  G.region as Region
        ,A.Name as AgencyName 
        ,A.AgencyId
        , sum(L.LoanAmount) as LoanAmount 
        ,Row_Number() over (Partition By G.region  order by sum(L.LoanAmount)  desc) as RNo
        from dw.FFLoan L

    inner join dw.dimborrower B on L.BorrowerId = B.BorrowerId 
    inner join dw.DIMGeography G on G.GeographyId = B.GeographyId
    inner join dw.DIMAgency A on A.AgencyId = L.Agency 
    group by G.region, A.Name, A.AgencyId


)
Select * from CTE 
where RNo <=5
order by LoanAmount desc

OTHER TIPS

You can do this using the window function row_number(). This orders rows within a group (say region) by another column (say sum(LoanAmount)). You can use window functions with aggregation functions, so the query looks like:

select region, AgencyName, AgencyId, LoanAmount
from (select g.region, a.Name as AgencyName, a.AgencyId, sum(l.LoanAmount) as LoanAmount,
             Row_Number() over (Partition By G.region  order by sum(l.LoanAmount) desc) as seqnum
      from dw.FFLoan l inner join
           dw.dimborrower b
           on l.BorrowerId = b.BorrowerId inner join
           dw.DIMGeography g
           on G.GeographyId = b.GeographyId inner join
           dw.DIMAgency A
           on a.AgencyId = l.Agency 
      group by g.region, a.Name, a.AgencyId
     ) t
where seqnum = 1
order by region, LoanAmount desc;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top