如何在sql和sqlite中按日期选择前1个数据顺序

时间:2016-01-14 07:40:52

标签: sql-server-2008

我的数据就是那样

Name   code   start_date   end_date    price 
shop1  7001   2013-01-01   9999-12-31  200 
shop1  7001   2015-12-01   9999-12-31  300 
shop1  7110   2015-05-25   9999-12-31  800 
shop1  7120   2015-05-25   9999-12-31  700 
shop1  7130   2013-01-01   9999-12-31  300 

我想通过一个查询在所有数据中通过start_date选择前1个数据顺序。

Name   code   start_date   end_date    price 
shop1  7001   2015-12-01   9999-12-31  300 
shop1  7110   2015-05-25   9999-12-31  800 
shop1  7120   2015-05-25   9999-12-31  700 
shop1  7130   2013-01-01   9999-12-31  300 

1 个答案:

答案 0 :(得分:5)

SELECT t1.Name, t1.code, t1.start_date, t1.end_date, t1.price
FROM prices t1
INNER JOIN
(
    SELECT code, MAX(start_date) AS maxDate
    FROM prices
    GROUP BY code
) t2
ON t1.code = t2.code AND t1.start_date = t2.maxDate
ORDER BY t1.start_date DESC