我的表数据就像这样..
ID Name Date Time Type
1 aaa 2014-07-01 00:00:00:000 9:35:43 In
1 aaa 2014-07-01 00:00:00:000 11:10:43 OUT
1 aaa 2014-07-01 00:00:00:000 11:35:43 In
1 aaa 2014-07-01 00:00:00:000 1:00:43 OUT
1 aaa 2014-07-01 00:00:00:000 1:35:43 In
1 aaa 2014-07-01 00:00:00:000 4:00:43 OUT
1 aaa 2014-07-01 00:00:00:000 4:10:43 In
1 aaa 2014-07-01 00:00:00:000 6:35:43 OUT
2 Baa 2014-07-01 00:00:00:000 9:35:43 In
2 Baa 2014-07-01 00:00:00:000 11:10:43 OUT
2 Baa 2014-07-01 00:00:00:000 11:35:43 In
2 Baa 2014-07-01 00:00:00:000 1:00:43 OUT
2 Baa 2014-07-01 00:00:00:000 1:35:43 In
2 Baa 2014-07-01 00:00:00:000 4:00:43 OUT
2 Baa 2014-07-01 00:00:00:000 4:10:43 In
2 Baa 2014-07-01 00:00:00:000 6:35:43 OUT
现在我想只获得第一个并且最后使用sql从表中获取detalis。我该怎么办请帮助我
答案 0 :(得分:0)
;WITH LoginCTE AS
(
SELECT ID,
Date,
MIN(Time) AS MinLogin
FROM Table
WHERE Type = 'In'
GROUP BY ID,
Date
),LogoutCTE AS
(
SELECT ID,
Date,
MAX(Time) AS MaxLogout
FROM Table
WHERE Type = 'Out'
GROUP BY ID,
Date
)
SELECT T.ID,
T.Name,
T.Date,
MinLogin,
MaxLogout
FROM Table T
JOIN LoginCTE I
ON T.ID = I.ID
T.Date = I.Date
JOIN LogoutCTE O
ON T.ID = O.ID
T.Date = O.Date
答案 1 :(得分:0)
试试这个:
select *
from <YOUR_TABLE_HERE> ttt
join (
select max(time) logout_time, name, date
from <YOUR_TABLE_HERE>
where type = 'Out'
group by name, date) max_date_table on ttt.name = max_date_table.name and ttt.date = max_date_table.date and max_date_table.logout_time = ttt.time
join (
select min(time) login_time, name, date
from <YOUR_TABLE_HERE>
where type = 'In'
group by name, date) min_date_table on ttt.name = min_date_table.name and ttt.date = min_date_table.date and ttt.time = min_date_table.login_time
order by name