日期:2014-05-20 浏览次数:20872 次
DECLARE @TB TABLE(名称 NVARCHAR(20), 时间 DATETIME,状态 NVARCHAR(20)) INSERT INTO @TB SELECT '汽车A',GETDATE(),'出发' UNION ALL SELECT '汽车B',GETDATE(),'返回' UNION ALL SELECT '汽车A',GETDATE(),'出发' UNION ALL SELECT '汽车B',GETDATE(),'返回' UNION ALL SELECT '汽车A',GETDATE(),'出发' UNION ALL SELECT '汽车B',GETDATE(),'返回' SELECT * FROM @TB SELECT DISTINCT A.名称,B.时间 AS '出发时间',C.时间 AS '返回时间' FROM @TB A LEFT JOIN @TB B ON A.名称=B.名称 LEFT JOIN @TB C ON A.名称=C.名称
------解决方案--------------------
--> Test Data: @T 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.出发时间,b.返回时间 from (select [名称], 出发时间=max(case [状态] when '出发' then [时间] end) from @T group by [名称]) a join (select [名称],返回时间=max(case [状态] when '返回' then [时间] end) from @t group by [名称]) b on a.名称=b.名称 order by [名称] --Drop --Result /* 名称 出发时间 返回时间 ----- ----------------------- ----------------------- 汽车A 2001-01-01 01:01:01.000 2001-01-01 02:02:02.000 汽车B 2001-01-01 03:03:03.000 2001-01-01 04:04:04.000 汽车C 2001-01-01 05:05:05.000 2001-01-01 06:06:06.000 汽车D 2001-01-01 07:07:07.000 NULL */
------解决方案--------------------
select [名称],
出发时间=max(case [状态] when '出发' then [时间] end),
返回时间=max(case [状态] when '返回' then [时间] end)
from @t group by [名称]
order by [名称]
create table #RR ( [Name] varchar(20), RDate datetime, NType varchar(20) ) insert into #RR select '汽车A','2001-1-1 1:1:1','NType' 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 [Name], max(case when NType='出发' then RDate else null end) '出发时间', max(case when NType='返回' then RDate else null end) '返回时间' from #RR group by [Name]