我有一个SQL select查询生成的以下数据。数据首先按ID递增,然后按AVO降序排列,如下所示:
+-------+----------------+------+-------+---------+----------+-----+
| ID | Link | Name | Type | Subtype | Domicile | AVO |
+-------+----------------+------+-------+---------+----------+-----+
| 11111 | www.aaaaa3.com | AAAA | FUND | 40 act | USA | 456 |
| 11111 | www.aaaaa2.com | AAAA | FUND | 40 act | USA | 456 |
| 11111 | www.aaaaa6.com | AAAA | FUND | 40 act | UK | 345 |
| 11111 | www.aaaaa1.com | AAAA | FUND | 40 act | USA | 123 |
| 11111 | www.aaaaa4.com | AAAA | FUND | 40 act | USA | |
| 11111 | www.aaaaa5.com | AAAA | FUND | 40 act | USA | |
| 22222 | www.bbbb1.com | BBBB | BANK | Inv | Canada | 897 |
| 22222 | www.bbbb5.com | BBBB | BANK | Inv | Brazil | 586 |
| 22222 | www.bbbb3.com | BBBB | BANK | Inv | Cayman | 357 |
| 22222 | www.bbbb2com | BBBB | BANK | Inv | Cayman | |
| 22222 | www.bbbb4.com | BBBB | BANK | Inv | Cayman | |
+-------+----------------+------+-------+---------+----------+-----+
我需要做的是每个ID只保留一行,每个ID的字段AVO中的值最大,并删除其他ID。如果任何给定ID存在AVO字段中的两个相同值(请参见上表中的前两行),则保留第一行并删除另一行。
我想我可以在VBA中为每个ID值使用For ... Next循环,但我宁愿在SQL中运行它。这甚至可能吗?是否可以在Access中的SQL删除查询中嵌套循环?
感谢您的协助。
答案 0 :(得分:0)
假设您已添加名为AN
的自动编号字段,则可以使用以下查询:
DELETE * FROM MyTable
WHERE AN NOT IN(
SELECT AN From (MyTable t1
INNER JOIN (SELECT Max(AN) AS MaxAN, ID, AVO FROM MyTable GROUP BY ID, AVO) t2 ON t1.AN = t2.MaxAN)
INNER JOIN (SELECT ID, Max(AVO) As MaxAVO FROM MyTable GROUP BY ID) t3 ON (t2.ID = t3.ID AND t2.AVO = t3.MaxAVO)
)