2013-08-19 87 views
1

我有一個價格表,包含目的地,價格和effective_dates這個價格。遞歸SQL查詢。選擇最後一個入口分組

我想得到一個與上一個價格的目的地清單。

示例表:

Destination | Code | Effective_date | Price 
Spain  | 34 | 2013-04-05  | 0.02 
Spain  | 34 | 2013-07-01  | 0.01 
Spain Mobile | 346 | 2013-04-05  | 0.07 
Spain Mobile | 346 | 2013-07-01  | 0.08 

例如,如果我搜索碼34我想西班牙2013-07-01西班牙移動2013-07-01 我嘗試用

SELECT * 
FROM carrier_fares AS cf1    
WHERE NOT EXISTS (
    SELECT * FROM carrier_fares AS cf2 
    WHERE code LIKE ? 
    AND cf1.effective_date < cf2.effective_date 
    ) 

該表有50,000個以上的條目。

回答

2
SELECT x.* 
    FROM carrier_fares x 
    JOIN 
     (SELECT destination 
       , MAX(effective_date) max_date 
      FROM carrier_fares 
      GROUP 
       BY destination 
     ) y 
     ON y.destination = x.destination 
     AND y.max_date = x.effective_date 

-- [WHERE code LIKE '34%'] 
; 
-1
SELECT * FROM (
    SELECT * FROM carriers_fares ORDER BY effective_date DESC 
) as t1 GROUP by effective_date, code