111,094
社区成员




SELECT [名称],[出发时间],[返回时间]
FROM [Table]
WHERE [状态] = '出发'
declare @m_sql varchar(8000)
set @m_sql='select car_name '
select @m_sql=@m_sql+', max(case state when '''+a.state+''' then convert(varchar(10),date_time) else ''0'' end ) as ['+a.state+']' from (select state from car group by state) as a
set @m_sql=@m_sql+' from car group by car_name'
exec(@m_sql)
select car_name ,
max(case state when '出发' then convert(varchar(10),date_time) else '0' end ) as [出发],
max(case state when '返回' then convert(varchar(10),date_time) else '0' end ) as [返回]
from car group by car_name
select A.Name, A.Time as outTime, B.inTime from dbo.Table_4 as A
left join
(select [Name], [Time] as inTime from dbo.Table_4 where [Status]='返回') as B
on A.Name = B.Name where A.Status='出发'
declare @T table ([名称] varchar(5),[时间] datetime,[状态] varchar(4))
insert into @T
select '汽车A','2001-1-1 1:1:1','出发' union all
select '汽车A','2001-1-1 2:2:2','返回' union all
select '汽车B','2001-1-1 3:3:3','出发' union all
select '汽车C','2001-1-1 5:5:5','出发' union all
select '汽车B','2001-1-1 4:4:4','返回' union all
select '汽车C','2001-1-1 6:6:6','返回' union all
select '汽车D','2001-1-1 7:7:7','出发'
--select * from @T
--Code
select A.名称,A.时间 as 出发时间,
B.时间 as 返回时间 from @T AS A
left join
(select 名称,时间 from @T where 状态= '返回')
as B
on A.名称=B.名称
where A.状态= '出发'