日期:2014-05-18  浏览次数:20592 次

交叉取时间
字段
SQL code

startDate  endDate
2012-1-1   2012-1-1
...         ...
2012-1-15  2012-1-16



表中数据是出差的记录
现在要把多条记录合成一条记录,开始日期取第一条的开始日期,结束日期取最后一条的结束日期

请大家帮忙

------解决方案--------------------
只取两条记录么。
------解决方案--------------------
SQL code

create table tb
(
 startdate datetime,
 enddate datetime
)


insert into tb
select '2012-1-1','2012-1-1' union all
select '2012-1-4','2012-1-6' union all
select '2012-1-15','2012-1-16' 


select MIN (startdate),MAX (enddate) from tb

------解决方案--------------------
SQL code

create table mpt
(startDate date, endDate date)

insert into mpt
select '2012-1-1', '2012-1-1' union all
select '2012-1-15', '2012-1-16'


with t as
(select row_number() over(order by (select 0)) rn,
startDate,endDate from mpt)
select (select startDate from t where rn=1) startDate,
(select top 1 endDate from t order by rn desc) endDate

startDate  endDate
---------- ----------
2012-01-01 2012-01-16

(1 row(s) affected)