2016-12-29 37 views
-1

因此,我需要選擇每個財政年度的記錄,但僅限於第一條記錄在同一財政年度。例如:如果條件與第一行相匹配,如何選擇表格中的最後一行

Acc_ref Fin_year Amount Balance Date 
123  2014  -10  80 01.06.2014 
123  2014  -10  90 01.05.2014 
123  2014  100  100 01.04.2014 
321  2014  -10  80 01.04.2014 
321  2013  -10  90 01.03.2014 
321  2013  100 100 01.02.2014 

在這種情況下,我想選擇最後一排,其中fin_year匹配的第一行的acc_ref和平衡。因此,我只希望看到123(acc_ref)和80(餘額)。

選擇acc_ref,日期,從表名平衡 其中(acc_ref,日期)在( 選擇acc_ref,MAX(如日期 從表名 組日期)由acc_ref)

但也想說,其中fin_year匹配最短日期fin_year

可以這樣做嗎?

+1

什麼數據庫平臺?請以表格格式顯示數據。不可能閱讀。 – OldProgrammer

+6

什麼是「第一排」?這不是一個SQL概念。表格表示無序集合。 –

回答

0

我不認爲如果這是一個很好的問題,但如果你有這樣的事情ID AUTO_INCREMENT,所以你可以使用它作爲第一個和最後,你可以寫一個SQL查詢,檢查min(ID)並顯示max(ID)

0

如果我理解這個問題,這是一個可能的解決方案。

我通過編號和Acc_ref排序行分區由Acc_ref, date,然後選擇第一行,如果YEAR(Date)比賽Fin_year

with cteB (Acc_ref, Fin_year, Amount, Balance, Date, Row) 
as 
(
    select Acc_ref, Fin_year, Amount, Balance, Date, 
      row_number() over (partition by Acc_ref order by Acc_ref, date) as Row 
    from 
     your_table 
) 
select Acc_ref, Fin_year, Amount, Balance, Date, Row 
from cteB 
where Row = 1 and Fin_year = year(Date); 
相關問題