2017-10-06 4 views
0

Ich habe eine Tabelle wie folgt aus:eine Zeile auswählen, basierend auf Monat und Jahr in SQL

ID |  Cost  | Month | Year | InMonth | InYear | 
-------------------------------------------------------- 
1081|  13000 | 5 | 2017 | 10 | 2016 | 
1081|  13500 | 9 | 2016 | 10 | 2016 | 
1081|  21000 | 2 | 2016 | 10 | 2016 | 
1229|  6500 | 7 | 2017 | 10 | 2016 | 
1229|  7800 | 5 | 2016 | 10 | 2016 | 
1312| 110000 | 8 | 2017 | 10 | 2016 | 
1312| 120000 | 5 | 2017 | 10 | 2016 | 
1312|  99000 | 5 | 2016 | 10 | 2016 | 

Ich möchte auf InMonth = Monat und InYear = Jahr basiert Ergebnisdaten/Zeile zeigen. Wenn InMonth nicht gleich wie Month und InYear nicht wie Year, erhalten Sie vorherige Daten/Zeile. Wie folgt aus:

ID |  Cost  | Month | Year | InMonth | InYear | 
1081|  13500 | 9 | 2016 | 10 | 2016 | 
1229|  7800 | 5 | 2016 | 10 | 2016 | 
1312|  99000 | 5 | 2016 | 10 | 2016 | 

ich das versucht:

select "ID", "Cost", "Month", "Year" 
from (select "ID", "Cost", "Month", "Year", 
    case when "InMonth">="Month" and "InYear">="Year" 
    then row_number() over(partition by "ID" order by "Year" desc, "Month" desc) 
    else 0 
end as RN 
from price_history 
) X 
where RN<>0 

SQL Fiddle: http://sqlfiddle.com/#!15/7b8b6f/1/0

+0

Wäre es nicht besser, sich zu bewegen '„InMonth“> =„Monat“und„InYear“> =„Year“', wo Klausel .. Sie werden nicht einmal brauchen ' row_number' dann – GurV

+0

Warum erscheint 9 in Ihrem gewünschten Ergebnis und 2 nicht? –

+0

Vielen Dank, ich habe das Problem gelöst –

Antwort

1

Sorry, ich kann nur posten. Ich benutze diesen Code:

select "ID", "Cost", "Month", "Year", "rn" 
from (select "ID", "Cost", "Month", "Year", 
    row_number() over(partition by "ID" order by "Year" desc, "Month" desc) 
    as RN 
from price_history where "InMonth">="Month" and "InYear">="Year" 
) X 
where RN=1 
1

Sie Postgres verwenden. Ich würde vorschlagen, :

select distinct on (id) t.* 
from t 
where year < inyear or 
     (year = inyear and month <= inmonth) 
order by id, year desc, month desc; 
+0

Danke, ich werde das nächste Problem versuchen –

Verwandte Themen