查询最新日期记录

时间:2016-03-01 06:33:34

标签: mysql sql sql-server

我的桌子

id  home  datetime     player   resource
---|-----|------------|--------|---------
1  | 10  | 04/03/2009 | john   | 399 
2  | 11  | 04/03/2009 | juliet | 244
5  | 12  | 04/03/2009 | borat  | 555
3  | 10  | 03/03/2009 | john   | 300
4  | 11  | 03/03/2009 | juliet | 200
6  | 12  | 03/03/2009 | borat  | 500
7  | 13  | 24/12/2008 | borat  | 600
8  | 13  | 01/01/2009 | borat  | 700

结果将是选择最近2个日期之间的所有记录如何为此

编写查询

1 个答案:

答案 0 :(得分:4)

您可以使用DENSE_RANK

SELECT id, home, [datetime], player, resource
FROM (
  SELECT id, home, [datetime], player, resource,
         DENSE_RANK() OVER (ORDER BY [datetime] DESC) AS rnk
  FROM mytable) AS t
WHERE t.rnk <= 2

DENSE_RANK为与最新日期值相关的所有记录分配值1,为与第二个最新日期相关的所有记录分配值2值。

<强>输出:

id  home    datetime            player  resource
=================================================
7   13  2009-12-12 02:00:00.000 borat   600
1   10  2009-04-03 03:00:00.000 john    399
2   11  2009-04-03 03:00:00.000 juliet  244
5   12  2009-04-03 03:00:00.000 borat   555

在MySQL中,您可以使用变量模拟DENSE_RANK

SELECT id, `datetime`, player, resource
FROM (
  SELECT id, `datetime`, player, resource,
         @rn := IF(@dt = `datetime`, @rn, 
                   IF(@dt := `datetime`, @rn + 1, @rn + 1)) AS rnk
  FROM mytable
  CROSS JOIN (SELECT @rn := 0, @dt := '1900-01-01') AS vars
  ORDER BY `datetime` DESC) AS t
WHERE t.rnk <= 2

Demo here