SQL Server how to fetch single record from multiple resultset per condition -




i have table has multiple records per year. pick latest record current year. if there not record current year, pick record has latest value year field. can help?

i have below query in sql server 2008 v2.

declare @currentyear int set @currentyear = year(getdate()) select account,        column2,        column3,        year_c   year_c = @currentyear 

if there multiple records in table current year 2017, query return records. select latest record list. also, need select 1 record combination of account & year_c.

this query return latest record per account:

declare @currentyear int set @currentyear = year(getdate()) select * (     select row_number() on (partition account order year_c desc) rn,            account,            column2,            column3,            year_c     year_c <= @currentyear ) results rn = 1 

the trick select records , assign them row-index per each account (partition), sorted year descending. select ones row-index of 1 latest per account.

hope helps.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -