我在编写Access sql查询时遇到问题。我想在每个月选择带有id的行,在以后的几个月内没有重复,如果id出现在1月和2月,则应在2月份省略等。 当然我有全年的数据。 示例数据
Month id
__________
01-15 1
01-15 2
01-15 3
01-15 5
01-15 2
02-15 1
02-15 4
02-15 4
02-15 5
03-15 1
03-15 9
结果应为
01-15 1
01-15 2
01-15 3
01-15 5
01-15 2
02-15 4
02-15 4
03-15 9
到目前为止,我用循环
为它制作vba宏Dim db As DAO.Database
Set db = CurrentDb
Dim list As String, sql As String, okres As String
Dim i As Integer
For i = 1 To 12 Step 1
If i < 10 Then
okres = "0" & i
Else
okres = i
End If
sql = "SELECT DISTINCT [ID] INTO SRC from [TMP] where okres = '" & okres & "-15';"
db.Execute sql, dbFailOnError
sql = "DELETE [TMP].* FROM [TMP] WHERE [ID] in (SELECT * from SRC) and okres <> '" & okres & "-15';"
db.Execute sql, dbFailOnError
sql = "DROP TABLE SRC"
db.Execute sql, dbFailOnError
Next i
它运行正常,但我想在一个SQL查询中编写它。
答案 0 :(得分:0)
您可以使用exists
子查询来查找重复前一行的行:
DELETE yt1
FROM YourTable yt1
WHERE EXISTS
(
SELECT *
FROM YourTable yt2
WHERE yt1.ID = yt2.ID AND
mid(yt2.TheMonth, 3, 2) + mid(yt2.TheMonth, 1, 2) <
mid(yt1.TheMonth, 3, 2) + mid(yt1.TheMonth, 1, 2)
)
where
条件查找:
MM-YY
转换为YYMM
,以便进行比较。