我有2个表,Jobs和AdminUsersLog。 AdminUsersLog包含对Jobs中每个作业记录执行的操作的日志。
我正在尝试检索已闲置超过7天的作业列表。下面的SQL似乎是为每个作业提取所有日志条目,因此从日志中提取旧条目,当然这些条目总是超过7天。
我需要为AdminUsersLog.ulDate超过7天的每个作业检索一条记录。
SELECT DISTINCT Jobs.ID, Jobs.bStatus AS jStatus, Jobs.sID, Jobs.insDate, Jobs.statusLabel, Jobs.cID, AdminUsersLog.ulDate, AdminUsersLog.ulJobType
FROM AdminUsersLog LEFT JOIN Jobs
ON (AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1)
WHERE AdminUsersLog.ulJobType = 1
AND (SELECT TOP(1) AdminUsersLog.ulDate FROM AdminUsersLog WHERE AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1) < DATEADD(dd,-7,GETDATE())
AND Jobs.bStatus < 8
前X名结果; http://pastebin.com/RcvxbxCV
答案 0 :(得分:1)
您设置了您的upDate列
AS
SELECT CONVERT(DATE,ulDate) AS ulDate
选择字段
SELECT CAST('2014-01-23 15:23:42.093' AS DATE) like this
因为你的upDate字段并不明显
查询SET AS
SELECT DISTINCT Jobs.ID, Jobs.bStatus AS jStatus, Jobs.sID, Jobs.insDate, Jobs.statusLabel, Jobs.cID,
CONVERT(DATE,AdminUsersLog.ulDate) AS ulDate, AdminUsersLog.ulJobType
FROM AdminUsersLog
LEFT JOIN Jobs ON (AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1)
WHERE AdminUsersLog.ulJobType = 1
AND (SELECT TOP(1) AdminUsersLog.ulDate FROM AdminUsersLog WHERE AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1) < DATEADD(dd,-7,GETDATE())
AND Jobs.bStatus < 8
答案 1 :(得分:1)
看看
SELECT TOP(1) AdminUsersLog.ulDate
FROM AdminUsersLog
WHERE AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1
这将为您提供工作条目。这可以是任何匹配的条目,因为您没有为TOP表达式指定排序顺序。通常随机挑选的条目将是旧的。因此要么指定排序顺序:
SELECT TOP(1) AdminUsersLog.ulDate
FROM AdminUsersLog
WHERE AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1
ORDER BY ulDate DESC
或者只是使用MAX:
SELECT MAX(AdminUsersLog.ulDate)
FROM AdminUsersLog
WHERE AdminUsersLog.ulJobID = Jobs.ID AND AdminUsersLog.ulJobType = 1