SQL中查询一天的刷卡记录等于四次的,并且在2015-3-1 11:00:00到2015-3-1 13:00:00之间的,要求把第一次刷卡和第四次刷卡超过40分钟的选出。
Select * from
(SELECT * FROM (SELECT * FROM logtablE WHERE logid in
(SELECT logid FROM logtable WHERE logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00' GROUP BY Logid HAVING COUNT(*)=4) AND logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00' ) A
ORDER by logname,logtime)
WHERE logid in(select logid FROM A GROUP BY A HAVING DATEDIFF(MINUTE,MIN(logtime),MAX(logtime))>40)
提示:除非同时指定了 TOP,否则 ORDER BY 子句在视图、内嵌函数、派生表和子查询中无效。
能不能帮我查改一下谢谢!
------解决思路----------------------
如果你真是SQL2005,可以这样查
;WITH CTE AS(
SELECT logid,logtime
,COUNT(1)OVER(PARTITION BY logid)C
,MIN(logtime)OVER(PARTITION BY logid)Minlogtime
,MAX(logtime)OVER(PARTITION BY logid)Maxlogtime
FROM logtable
WHERE logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00'
)
SELECT logid,logtime
FROM CTE
WHERE C=4 AND DATEDIFF(MINUTE,Minlogtime,Maxlogtime)>=40
------解决思路----------------------
Select * from
(SELECT * FROM logtablE WHERE logid in
(SELECT logid FROM logtable WHERE logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00' GROUP BY Logid HAVING COUNT(*)=4)
AND logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00' ) A
WHERE logid in(select logid FROM A GROUP BY logid HAVING DATEDIFF(MINUTE,MIN(logtime),MAX(logtime))>40)
ORDER by logname,logtime
------解决思路----------------------
SELECT *
FROM logtablE a
INNER JOIN (
SELECT logid,MAX(logtime) AS MaxLogTime,MIN(logtime) AS MinLogTime
FROM logtable
WHERE logtime BETWEEN '2015-3-1 11:00:00' AND '2015-3-1 13:00:00'
GROUP BY Logid HAVING COUNT(*)=4) b ON a.logid=b.logid AND DATEDIFF(MINUTE,b.MinLogTime,b.MaxLogTime)>40