HI 我正在寻找一些帮助,我似乎无法理解自己如何加入工作。我有这个sql代码
select Persno'Name',convert(char(20), A_Date , 13)'Logins',acode
from atrail as LOGIN
where acode = 'LOGIN' OR acode = 'LOGOUT'
order by a_date desc
生成用户名列表以及登录和注销时。我想要实现的目标是在他们登录日期的日期旁边找到带有LOGOUT日期的花药列,以便在登录和退出时更容易看到。
由于
安迪
答案 0 :(得分:2)
这应该这样做:
select LOGIN.Persno AS Name,
LOGIN.a_date AS login_date, --//convert here as you like
LOGOUT.a_date AS logout_date --//convert here as you like
from atrail as LOGIN
left join atrail as LOGOUT
ON LOGOUT.Persno= LOGIN.Persno
AND LOGOUT.acode = 'LOGOUT'
AND LOGOUT.A_Date= (SELECT TOP 1 x.A_Date
FROM atrail x
WHERE x.Persno = LOGIN.Persno
AND x.A_Date >= LOGIN.A_Date
AND x.acode = 'LOGOUT'
ORDER BY x.A_Date)
where LOGIN.acode = 'LOGIN'
order by LOGIN.a_date desc
将以以下格式生成结果:
Name login_date logout_date
----------- ----------- -----------
pippo 2008-01-01 2008-01-03
答案 1 :(得分:0)
这可能是实现它的另一种方式:
SELECT Name, [LOGIN] as login_date, [LOGOUT] as logout_date
FROM
(
SELECT Persno Name,convert(char(20), A_Date , 13) Logins, acode
FROM atrail
WHERE acode = 'LOGIN' OR acode = 'LOGOUT'
ORDER BY a_date DESC
) AS login_table
PIVOT
(
MAX(Logins) FOR acode IN ([LOGIN],[LOGOUT])
) AS pvt_table
ORDER BY login_date DESC
这是考虑到每个登录日期都有一个注销日期,每个人只有一个登录和一个注销行。