日期:2014-05-17 浏览次数:20590 次
CREATE TABLE #UserLogin
(
LoginTime DATETIME DEFAULT GETDATE(),
Account_ID VARCHAR(16),
LoginState INT
)
GO
INSERT INTO #UserLogin
SELECT '2013-05-15 08:01:03','zy_luopeng',1 UNION ALL
SELECT '2013-05-15 10:30:03','zy_luopeng',0 UNION ALL
SELECT '2013-05-15 14:17:03','zy_luopeng',1 UNION ALL
SELECT '2013-05-15 19:50:03','zy_luopeng',0
GO
INSERT INTO #UserLogin
SELECT '2013-05-15 08:01:03','test',0 UNION ALL --表示从昨天到今天一直在
SELECT '2013-05-15 19:30:03','test',1 --表示一直玩到今天通宵
GO
SELECT * FROM #UserLogin
/*
想要获取的结果
第一步: 到这步实在想了半天都不知道要怎么得到这种结果。
这样写又不对。。
SELECT Account_ID,
CASE WHEN LoginState = 1 THEN
LoginTime ELSE 0 END AS '上线时间' ,
CASE WHEN LoginState = 0 THEN
LoginTime ELSE 0 END AS '下线时间'
FROM #UserLogin
=========================================================================
Account UpTime DownTime
=========================================================================
zy_luopeng 2013-05-15 08:01:03.000 2013-05-15 10:30:03.000
zy_luopeng 2013-05-15 14:17:03.000 2013-05-15 19:50:03.000
test 2013-05-15 00:00:00.000 2013-05-15 08:01:03.000
test 2013-05-15 19:30:03.000 2013-05-15 23:59:59.999
第二步:
UpTime DownTime SumAccount
====================================================================================
2013-05-15 08:00:00 2013-05-15 09:00:00 1
2013-05-15 09:00:00 2013-05-15 10:00:00 1
.
.
.
2013-05-15 19:00:00 2013-05-15 20:00:00 2
.
.
.
*/