frist这是checkinout表
select userid , checktime from checkinout where
USERID=467 and CHECKTIME>'2014-10-24 00:00:00.000' order by chcktime
userid checktime
467 2014-10-24 02:18:20.000
467 2014-10-24 17:04:43.000
467 2014-10-25 02:31:40.000
467 2014-10-25 17:13:38.000
467 2014-10-25 20:59:10.000
467 2014-10-28 02:55:57.000
467 2014-10-28 17:57:12.000
467 2014-10-29 17:13:35.000
467 2014-10-30 02:35:47.000
467 2014-10-30 17:17:56.000
467 2014-10-31 03:02:50.000
467 2014-10-31 17:19:18.000
467 2014-11-01 02:42:18.000
467 2014-11-01 17:16:14.000
467 2014-11-02 02:44:00.000
467 2014-11-03 17:20:10.000
467 2014-11-04 02:38:57.000
467 2014-11-04 17:33:54.000
467 2014-11-05 02:15:50.000
467 2014-11-05 17:14:25.000
我有这个查询
SELECT USERID,MIN(checktime) AS InTime,MAX(checktime) AS OutTime
FROM checkinout
where USERID=467 and CHECKTIME>'2014-10-24 00:00:00.000'
GROUP BY USERID,DATEDIFF(dd,0,DATEADD(hh,-4,checktime))
HAVING MIN(checktime) <> MAX(checktime)
AND MAX(DATEADD(hh,-4,checktime))-DATEDIFF(dd,0,DATEADD(hh,-4,checktime)) > '22:00'
ORDER BY MIN(checktime)
userid InTime OutTime
467 2014-10-24 17:04:43.000 2014-10-25 02:31:40.000
467 2014-10-29 17:13:35.000 2014-10-30 02:35:47.000
467 2014-10-30 17:17:56.000 2014-10-31 03:02:50.000
467 2014-10-31 17:19:18.000 2014-11-01 02:42:18.000
467 2014-11-01 17:16:14.000 2014-11-02 02:44:00.000
467 2014-11-03 17:20:10.000 2014-11-04 02:38:57.000
467 2014-11-04 17:33:54.000 2014-11-05 02:15:50.000
我需要在输出中使用null,如
userid InTime OutTime
467 Null 2014-10-24 02:18:20.000
467 2014-10-24 17:04:43.000 2014-10-25 02:31:40.000
467 2014-10-25 17:13:38.000 Null
467 2014-10-25 20:59:10.000 Null
467 2014-10-28 17:57:12.000 Null
467 Null 2014-10-28 02:55:57.000
467 2014-10-29 17:13:35.000 2014-10-30 02:35:47.000
467 2014-10-30 17:17:56.000 2014-10-31 03:02:50.000
467 2014-10-31 17:19:18.000 2014-11-01 02:42:18.000
467 2014-11-01 17:16:14.000 2014-11-02 02:44:00.000
467 2014-11-03 17:20:10.000 2014-11-04 02:38:57.000
467 2014-11-04 17:33:54.000 2014-11-05 02:15:50.000
此表用于指纹签入和签出,用户ID 467从下午5点转移到凌晨2点
答案 0 :(得分:0)
目前的数据结构无法实现。
您当前的表格是来自userid -> checktime
的关系,现在您想要以某种方式将checktime
拆分为intime
和outtime
,但如果没有更多的话,这是不可能的信息。
你想白天分组,那很好。如果您在一天内找到2个checktime
条目,则您知道较低的一个是intime
,而较高的一个是outtime
。但是,如果只有一个checktime
条目,则您无法确定它是in
还是out
。唯一的方法是说&#34;如果它是单个checktime
并且它在12:00:00之前,那么它必须是intime
。如果在12:00:00之后,则必须是outtime
&#34;。
换句话说:如果intime = null
或outtime = null
在某一天有checktime
个条目,您会如何决定?
另一点是:您如何在一天内处理3个(或更多)checktime
条目?
答案 1 :(得分:0)
你非常接近!
这是一个快速解决方案(未经过测试,但我希望你能得到这个想法):
Select USERID
,MIN(Case When convert(time, checktime) > '12:00:00' Then checktime End) AS InTime
,MAX(Case When convert(time, checktime) <= '12:00:00' Then checktime End) AS OutTime
From checkinout
Where USERID=467 and CHECKTIME>'2014-10-24 00:00:00.000'
Group By USERID, DATEDIFF(dd,0,DATEADD(hh,-4,checktime))
Order By 2