问个问题,有下表table1
name year sell
Jeck 2005 345
Jeck 2006 500
Jeck 2007 876
小王 2005 562
小王 2006 786
小王 2007 247
通过上表得到下表的结果(不可以用游标、子查询)
name year sell last_year
Jeck 2005 345 null
Jeck 2006 500 245
Jeck 2007 876 500
小王 2005 562 null
小王 2006 786 562
小王 2007 247 786
name year sell
Jeck 2005 345
Jeck 2006 500
Jeck 2007 876
小王 2005 562
小王 2006 786
小王 2007 247
通过上表得到下表的结果(不可以用游标、子查询)
name year sell last_year
Jeck 2005 345 null
Jeck 2006 500 245
Jeck 2007 876 500
小王 2005 562 null
小王 2006 786 562
小王 2007 247 786
if object_id('table1')is not null drop table table1
go
create table table1(name varchar(6), year varchar(5) , sell int)
insert table1 select 'Jeck' , 2005 , 345
insert table1 select 'Jeck' , 2006 , 500
insert table1 select 'Jeck' , 2007 , 876
insert table1 select '小王' , 2005 , 562
insert table1 select '小王' , 2006 , 786
insert table1 select '小王' , 2007 , 247
select t.*,last_year=(select sell from table1 where name=t.name and [year]=t.[year]-1) from table1 t
/*name year sell last_year
------ ----- ----------- -----------
Jeck 2005 345 NULL
Jeck 2006 500 345
Jeck 2007 876 500
小王 2005 562 NULL
小王 2006 786 562
小王 2007 247 786
*/
id Yid T1 T2 ...
1 s 2
2 1 22 22s
3 ss 12
4 2 ss2 2给定一个 id ,如何能找出 所有id和yid 有关系的 数据集?
id Yid T1 T2 ...
1 s 2
2 1 22 22s
4 2 ss2 2
这里边不是用上了子查询吗?
if object_id('table1')is not null drop table table1
go
create table table1(name varchar(6), year varchar(5) , sell int)
insert table1 select 'Jeck' , 2005 , 345
insert table1 select 'Jeck' , 2006 , 500
insert table1 select 'Jeck' , 2007 , 876
insert table1 select '小王' , 2005 , 562
insert table1 select '小王' , 2006 , 786
insert table1 select '小王' , 2007 , 247
select a.*,b.sell from table1 a left join table1 b on a.name=b.name and b.[year]=a.[year]-1
/*name year sell sell
------ ----- ----------- -----------
Jeck 2005 345 NULL
Jeck 2006 500 345
Jeck 2007 876 500
小王 2005 562 NULL
小王 2006 786 562
小王 2007 247 786
*/