如果重复,请选择最近的记录

时间:2016-07-06 09:44:33

标签: sql ms-access-2010

所以我一直在讨论这个,主要是因为我正在访问2010年,我在互联网上找到的大多数查询都有不能访问的命令。

id    name    date        qty       created
====================================================
1     abc     01/2016     20        06/07/2016 11:00
2     abc     02/2016     20        06/07/2016 11:00
3     abc     03/2016     20        06/07/2016 11:00
4     abc     01/2016     30        06/07/2016 13:00

我需要拿出这样的记录集:

id    name    date        qty       created
====================================================
2     abc     02/2016     20        06/07/2016 11:00
3     abc     03/2016     20        06/07/2016 11:00
4     abc     01/2016     30        06/07/2016 13:00

创建的字段只是一个时间戳,日期字段是“截止日期”。基本上我需要为每个名字和日期提取最新的数量。 ID是唯一的,所以我可以使用它,如果它更容易。 到目前为止我有:

SELECT m1.date, m1.name, m1.created
FROM table AS m1 LEFT JOIN table AS m2 ON (m1.created < m2.created) AND 
(m1.date = m2.date)
WHERE m2.created IS NULL;

但是这只给了我最近的冲突数据,即。我的例子中的记录n°4也需要另外两个记录。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试使用NOT EXISTS()

SELECT * FROM YourTable t
WHERE NOT EXISTS(SELECT 1 FROM YourTable s
                 WHERE t.date = s.date and s.created > t.created
                   AND t.name = s.name)

我认为你也错过了一个条件所以我已经添加了它:

and t.name = s.name

您没有标记您的RDBMS,如果您的SQL-Server / Oracle / Postgresql可以使用ROW_NUMBER()

SELECT s.date, s.name, s.created FROM (
    SELECT t.*,
           ROW_NUMBER() OVER(PARTITION BY t.date,t.name ORDER BY t.created DESC) as rnk
    FROM YourTable t) s
WHERE s.rnk = 1

答案 1 :(得分:0)

试试这个:

SELECT m1.date, m1.name, m1.qty, m1.created
FROM table AS m1
JOIN (
   SELECT date, name, MAX(created) AS created
   FROM table 
   GROUP BY date, name
) AS m2 ON m1.date = m2.date AND m1.name = m2.name AND m1.created = m2.created