永久循环sql

7cwmlq89  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(364)

我试图找到所有的工作人员没有登录在过去6个月,所以我有这个代码。它似乎一直在循环,但我不知道为什么

--select all staff not logged on in the last 6 months
SELECT
[fkStaffId],
[dteLogon]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[fkStaffId]
NOT IN
(--select all staff logged on in the last 6 months
    SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE()) --this is a list of each staffID
                                               --logged on in the last 6 months
)
ORDER BY [dteLogon] DESC

有人知道为什么吗?
如果我只是执行

SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE())

就其本身而言,我得到了一个大小合理的309行的列表,大约是我期望的数目,然而,上次我试图运行整个代码时,它在25分钟后仍然在执行!!

luaexgnf

luaexgnf1#

我会做一个 GROUP BY ,并使用 HAVING 仅返回最近未登录的用户:

SELECT 
    [fkStaffId], MAX([dteLogon])
FROM
    [dbo].[tbl_Staff_Logon]
GROUP BY [fkStaffId]
HAVING MAX([dteLogon]) < DATEADD(MONTH, -6, GETDATE())

相关问题