Recently, in the forum, I met a lot more difficult sql problem, although they can be resolved, but found a few days later, they can not remember, forget the solution of.
So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.
How to solve users online landing time - the hour and minute calculation.
http://bbs.csdn.net/topics/390613823
I want users online time, the format is: 08: 00 and when 8:43 this online format length results.
I try to check the documentation sql, also Baidu a lot. But no application in this regard.
I have also tried to write a lot but I can not.
I can get the total number of minutes online, or the total number of seconds. Not inflicted desired format.
This is my code:
SELECT TA [User], (the DATEDIFF (mi The, ta.time, tb.time)) from.
(SELECT * WHERE T1.operate = Tl from 'the Login') AS TA
Inner the Join
(SELECT * from WHERE T1.operate = Tl 'Zimbabwe Logout') AS TB
ON TA. [User] = TB. [User]
-------------------------- ----------
or write:
SELECT TA [User], Cast (DATEDIFF (hour, ta.time, tb.time) AS VARCHAR) +. ':' + Cast (the DATEDIFF (MINUTE, TA .time, tb.time) AS VARCHAR)
from
(SELECT [User], [Time] from Tl WHERE [Operate] = 'Login') AS TA
Inner the Join
(SELECT [User], [Time] from Tl WHERE [Operate] = 'Zimbabwe Logout') AS TB
. ON TA [User] = TB [User].;
Both versions can not achieve the desired results. At the request of the god of guidance, help give a solution.
I finished testing, hair renderings.
My solution:
method 1:
-
drop
table t1
-
-
create
table T1
-
(
-
[
user]
varchar(
30),
-
operate
varchar(
10),
-
time datetime
-
)
-
-
insert
into T1
-
select
'LiMing',
'Login',
'2010/10/24 8:03'
union all
-
select
'WangYi',
'Login',
'2010/10/24 8:14'
union all
-
select
'WangYi',
'Logout',
'2010/10/24 16:14'
union all
-
select
'LiMing',
'Logout',
'2010/10/24 16:14'
-
-
-
select [
user],
-
cast(
cast(
round(
interval *
1.0 /
60,
0,
1)
as
int)
as
varchar) +
':' +
-
case
when
interval *
1.0 %
60 <>
0
-
then
cast(
cast(
round(
interval *
1.0 %
60,
0,
1)
as
int)
as
varchar)
-
else
'00'
-
end
-
from
-
(
-
select T1.[
user],
-
DATEDIFF(
MINUTE,t1.time,t2.time)
as
interval
-
-
from T1
-
inner
join T1 t2
-
on t1.[
user] = t2.[
user]
-
and t1.operate =
'login'
-
and t2.operate =
'logout'
-
)a
-
/*
-
user (无列名)
-
LiMing 8:11
-
WangYi 8:00
-
*/
Method 2:
-
--方法2.
-
select [
user],
-
convert(
varchar(
5),
DATEADD(
MINUTE,
interval,
time),
114)
-
from
-
(
-
select T1.[
user],
-
convert(
varchar(
10),t1.time,
120)
as
time,
-
DATEDIFF(
MINUTE,t1.time,t2.time)
as
interval
-
-
from T1
-
inner
join T1 t2
-
on t1.[
user] = t2.[
user]
-
and t1.operate =
'login'
-
and t2.operate =
'logout'
-
)a
-
/*
-
user (无列名)
-
LiMing 08:11
-
WangYi 08:00
-
*/
So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.