如何根据截止日期获取最新记录?

时间:2015-05-20 12:58:53

标签: sql sql-server tsql

我有下表:

    $scope.data.children = _.filter($scope.data.components, function (item) {
        return item.selected == "true";
    });

我应该如何获得最新记录?我尝试过类似的东西:

+------------------------------------+
|     Number  Name     Date          |
+------------------------------------+
| 1   1050    Name1    2015-01-01    |
| 2   1051    Name2    2015-04-27    |
| 3   1057    Name3    2015-04-27    |
+------------------------------------+

我期待得到最新的记录,但由于我的条款,我得到了所有三个。有没有办法在保持SELECT number, name, MAX(DATE) AS recent_date FROM Recent_Table HAVING recent_date < '2015-05-19' GROUP BY number, name 的同时解决这个问题?感谢。

预期输出为:

having

4 个答案:

答案 0 :(得分:1)

试试这个

select number, name, date
from Recent_Table
where Date = (SELECT MAX(DATE) AS recent_date
              FROM Recent_Table
              WHERE DATE < '2015-05-19')

name列没有having子句存在问题。我认为你不需要having

Sql fiddle演示

答案 1 :(得分:1)

SELECT 
number,
name,
DATE AS recent_date
FROM Recent_Table
WHERE DATE = (SELECT MAX(t2.DATE)
                 FROM Recent_Table t2
                 WHERE t2.number = t1.number)

答案 2 :(得分:0)

SELECT number, name, MAX(DATE) AS recent_date
FROM Recent_Table
WHERE DATE <= MAX(DATE)
GROUP BY number, name

将返回最新条目的值

答案 3 :(得分:0)

让我猜一下

 SELECT number, name
 FROM   Recent_Table
 WHERE recent_date >= (Select Max(Date) FROM Recent_Table)