我有一组记录,希望显示符合某些条件的最新记录。我过去做错了,因为它会先提取最近的记录,然后尝试匹配条件,这会导致某些记录消失。我想让查询执行的操作是首先找到符合条件的记录,然后让它从该数据集中提取最新记录。我需要让此查询在Access中插入表。
我以为我已经对它进行了整理,但是出现错误“您的查询未将指定的表达式'SufGrpID'作为聚合函数的一部分
数据示例:
查询运行时,我希望结果为:
数据示例:
SufGrpID 03将被从集合中删除,因为它不是CaseID 123的最新记录
SufGrpID 04将被从集合中删除,因为它不是SufTypeID 14,也不是状态F
How the data looks
+----------+---------+-------------------------+-----------+--------+
| SufGrpID | CaseID | CreateDate | SufTypeID | Status |
+----------+---------+-------------------------+-----------+--------+
| 01 | 123 | 2010-08-20 07:42:32.000 | 14 | F |
| 02 | 234 | 2010-04-28 10:33:56.000 | 14 | F |
| 03 | 123 | 2010-04-20 10:05:04.000 | 14 | F |
| 04 | 345 | 2010-08-20 11:18:42.000 | 12 | I |
| 05 | 345 | 2010-04-20 11:18:42.000 | 14 | F |
+----------+---------+-------------------------+-----------+--------+
Here's the code that did not work for me...
INSERT INTO [aStudent Base Data] ( [Self Suff ID], [Self Suff Create Date] )
SELECT dbo_sufscrgrp.SufGrpID, Max(dbo_sufscrgrp.CreateDate)
FROM dbo_sufscrgrp
WHERE (((dbo_sufscrgrp.SufTypeID)=14) AND ((dbo_sufscrgrp.Status)="F"))
GROUP BY dbo_sufscrgrp.CaseID;
What I'd like the results to be. (EDITED at 1:33 CST)
+--------------+------------------------+
| Self Suff ID | Self Suff Create Date |
+--------------+------------------------+
| 01 | 2010-08-20 07:42:32.000 |
| 02 | 2010-04-28 10:33:56.000 |
| 05 | 2010-04-20 11:18:42.000 |
+--------------+-------------------------+
感谢您的帮助!
答案 0 :(得分:1)
基于最小数据集示例,请考虑:
SELECT dbo_sufscrgrp.*
FROM dbo_sufscrgrp
WHERE SufGrpID
IN (SELECT TOP 1 SufGrpID FROM dbo_sufscrgrp As Dupe
WHERE Dupe.CaseID=dbo_sufscrgrp.CaseID AND SufTypeID=14 and Status="F"
ORDER BY Dupe.CreateDate DESC, Dupe.SufGrpID DESC);