日期:2014-05-16  浏览次数:20499 次

查询一周第一天和最后一天数据的问题
sid sdate svol
......
s1 2013-12-10 20
s1 2013-12-12 24
s1 2013-12-13 23
s1 2013-12-14 23

s2 2013-12-16 25
s2 2013-12-17 26
s2 2013-12-19 24

s3 2013-12-23 18
s3 2013-12-24 20
s3 2013-12-25 19
s3 2013-12-26 21
s3 2013-12-27 20
......
数据如上,想求一周的第一天和最后一天的数据
查询结果是这样
s1 2013-12-10 20
s1 2013-12-14 23

s2 2013-12-16 25
s2 2013-12-19 24

s3 2013-12-23 18
s3 2013-12-27 20
------解决方案--------------------

create table test (sid nvarchar(5),sdate datetime,svol int)
insert into test 
select 's1','2013-12-10',20 union all
select 's1','2013-12-12',24 union all
select 's1','2013-12-13',23 union all
select 's1','2013-12-14',23 union all
select 's2','2013-12-16',25 union all
select 's2','2013-12-17',26 union all
select 's2','2013-12-19',24 union all
select 's3','2013-12-23',18 union all
select 's3','2013-12-24',20 union all
select 's3','2013-12-25',19 union all
select 's3','2013-12-26',21 union all
select 's3','2013-12-27',20

select a.sid,
sdate=MIN(a.sdate),
svol=( select svol 
from test 
where sid=a.sid 
and sdate =(
select MIN(sdate) 
from test 
where sid=a.sid
)
)
from test a
group by a.sid
union 
select a.sid,
sdate=MAX(a.sdate),
svol=( select svol 
from test 
where sid=a.sid 
and sdate =(
select MAX(sdate) 
from test 
where sid=a.sid
)
)
from test a
group by a.sid
 
/*
s1 2013-12-10 00:00:00.000 20
s1 2013-12-14 00:00:00.000 23
s2 2013-12-16 00:00:00.000 25
s2 2013-12-19 00:00:00.000 24
s3 2013-12-23 00:00:00.000 18
s3 2013-12-27 00:00:00.000 20
*/

------解决方案--------------------



--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go 
create table [a](sid  char(2),sdate datetime,svol int)
insert [a]
select 's1', '2013-12-10', 20 union all
select 's1', '2013-12-12', 24 union all
select 's1', '2013-12-13', 23 union all
select 's1', '2013-12-14', 23 union all
select 's2', '2013-12-16', 25 union all
select 's2', '2013-12-17', 26 union all
select 's2', '2013-12-19', 24 union all
select 's3', '2013-12-23', 18 union all
select 's3', '2013-12-24', 20 union all
select 's3', '2013-12-25', 19 union all
select 's3', '2013-12-26', 21 union all
select 's3', '2013-12-27', 20 


select a.* from a ,
(
select sid ,min(sdate) as sdate from a group  by sid
union all
select sid ,max(sdate) as sda