需要计算与通过日期相关的最新结果

时间:2014-03-30 18:43:07

标签: sql postgresql-9.1

我在下面有一个表“匹配”

id      league home  away  start_time               match_score
----------------------------------------------------------------  
164247; 952;   1584; 1582; "2013-05-15 18:30:00+03" "{2,1}";
164248; 952;   1585; 881;  "2012-11-03 15:30:00+02" "{2,0}";
164249; 952;   1585; 882;  "2012-11-03 15:30:00+02" "{2,0}";
164250; 952;   1585; 1175; "2012-11-16 18:30:00+02" "{1,0}";
164251; 952;   1585; 1176; "2012-11-16 18:30:00+02" "{1,0}";
164252; 952;   1585; 1274; "2012-10-20 18:30:00+03" "{3,1}";
164253; 952;   1585; 1275; "2012-10-20 18:30:00+03" "{3,1}";
164254; 952;   1585; 1290; "2012-07-28 20:30:00+03" "{0,2}";
164255; 952;   1585; 1290; "2013-04-06 18:30:00+03" "{1,2}";
164256; 952;   1585; 1291; "2012-07-28 20:30:00+03" "{0,2}";
----------------------------------------------------------------

当球队(1585)在日期('2013-04-06')之前赢得他最新的主场比赛时,如何计算存储过程?

成绩结果:上面显示的表格中的id = 164253。

1 个答案:

答案 0 :(得分:1)

编辑:重新阅读这个问题,听起来你想要整行,而不仅仅是ID。

要获得完整行,您可以使用CTE;

WITH cte AS (
  SELECT *, ROW_NUMBER() OVER (ORDER BY start_time,id DESC) rn
  FROM match 
  WHERE home = 1585
    AND start_time < '2013-04-06'
    AND match_score[1] > match_score[2]
)
SELECT "id", "league", "home", "away", "start_time", "match_score"
FROM cte WHERE rn=1;

An SQLfiddle to test with