2014-05-14 72 views
0
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 

查詢我不能夠像 得到輸出首先我想先向東5 5,然後向北和向南,然後再向西。 我需要輸出僅5各頂貸款金額我堅持我有沒有能夠得到合適的輸出

的區域謝謝

+0

請提供期望我們給合適的解決方案 – samar

+0

使用窗函數(ROW_NUMBER)CTE樣本輸入數據和輸出。我正在嘗試一些東西。 – AK47

+0

你給寫4個相同的查詢 – Luv

回答

0

試試這個,

;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 
+0

請嘗試編輯後,列名更正。 – AK47

+0

thanx幫助...它的工作,但我也想設置貸款金額降序 – rb004

+0

現在請嘗試,如果答案是正確的,請標記爲有用。 – AK47

1

您可以使用窗口函數row_number()做到這一點。這可以通過另一列(比如sum(LoanAmount))對組內的行(比如區域)進行排序。您可以使用窗口函數與聚合函數,所以查詢的樣子:

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; 
+0

thanx幫助我 – rb004