我有一张桌子,叹了口气并注明了价值
**id Date Time Status**
01 1/02/12 8:10 Entry
01 1/02/12 9:00 Exit
01 1/02/12 9:10 entry
01 1/02/12 17:00 Exit
02 1/02/12 8:10 Entry
02 1/02/12 9:00 Exit
02 1/02/12 9:10 entry
02 1/02/12 17:00 Exit
**03 1/02/12 17:00 Exit**
我必须找出每个id的最小和最大时间
预期结果
**id Date Entry Exit **
01 1/02/12 8:10 17:00
02 1/02/12 8:10 17:00
请帮帮我
此代码工作正常但是只添加一个条目,只添加退出 我想要显示
id Date Entry Exit
---- -------- ----- -----
01 01/02/12 08:10 17:00
02 01/02/12 08:10 17:00
**03 01/02/12 Null 17:00**
请帮帮我 提前致谢
答案 0 :(得分:1)
根据使用的数据类型,这样的事情可能有效。
declare @T table
(
id varchar(2),
[Date] datetime,
[Time] varchar(5),
[Status] varchar(5)
)
insert into @T
select '01', '1/02/12', '8:10', 'Entry' union all
select '01', '1/02/12', '9:00', 'Exit' union all
select '01', '1/02/12', '9:10', 'entry' union all
select '01', '1/02/12', '17:00', 'Exit' union all
select '02', '1/02/12', '8:10', 'Entry' union all
select '02', '1/02/12', '9:00', 'Exit' union all
select '02', '1/02/12', '9:10', 'entry' union all
select '02', '1/02/12', '17:00', 'Exit'
select id,
convert(varchar(8), [Date], 1) as [Date],
convert(varchar(5), min([Time]), 108) as [Entry],
convert(varchar(5), max([Time]), 108) as [Exit]
from
(
select id,
[Date],
cast([Time] as datetime) as [Time],
row_number() over(partition by id order by [Date]+cast([Time] as datetime) asc) as rn1,
row_number() over(partition by id order by [Date]+cast([Time] as datetime) desc) as rn2
from @T
) as T
where T.rn1 = 1 or
T.rn2 = 1
group by id, [Date]
结果:
id Date Entry Exit
---- -------- ----- -----
01 01/02/12 08:10 17:00
02 01/02/12 08:10 17:00
答案 1 :(得分:0)
写下面的查询
Select * from MyTable where Time = (Select min(Time) from MyTable) and Status = 'Entry'
和
Select * from MyTable where Time = (Select max(Time) from MyTable) and Status = 'Exit'
编辑:
如果您希望对这些值进行单一查询,则可以按如下方式获取
SELECT DISTINCT MyTable.ID, MyTable.Date, MyTable.Time AS Entry, MyTable_2.Time AS
[Exit] FROM MyTable CROSS JOIN MyTable AS MyTable_2 WHERE (MyTable.Time =
(SELECT MIN(Time) AS Expr1 FROM MyTable AS MyTable_1)) AND (MyTable.Status = 'Entry')
AND (MyTable_2.Time = (SELECT MAX(Time) AS Expr2 FROM MyTable AS MyTable_3)) AND
(MyTable_2.Status = 'Exit')