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

望指教一SQL语句
表A:                         表B:
ID     Name                   ID       Year   Month   AID
1       张三                   1         2007       5         1      
2       李四                   2         2007       5         2
3       王五                   3         2007       5         3
                                  4         2007       6         1
                                  5         2007       6         2
                                  6         2007       7         1

表B的AID对应表对应表A的ID,现希望得到如下结果:

张三     2007   5
李四     2007   5
王五     2007   5
张三     2007   6  
李四     2007   6
王五     null   null
张三     2007   7    
李四     null   null
王五     null   null

------解决方案--------------------
之前有误,修正如下:

declare @A table(ID int,Name varchar(4))
insert into @a select 1, '张三 '
insert into @a select 2, '李四 '
insert into @a select 3, '王五 '

declare @B table(ID int,[Year] int,[Month] int,AID int)
insert into @B select 1,2007,5,1
insert into @B select 2,2007,5,2
insert into @B select 3,2007,5,3
insert into @B select 4,2007,6,1
insert into @B select 5,2007,6,2
insert into @B select 6,2007,7,1




select
a.Name,c.[Year],c.[Month]
from
@A a
cross join
(select distinct [Year],[Month] from @B) b
left join
@B c
on
a.ID=c.AID
and
b.[Year]=c.[Year] and b.[Month]=c.[Month]

/*

Name Year Month
---- ----------- -----------
张三 2007 5
李四 2007 5
王五 2007 5
张三 2007 6
李四 2007 6
王五 NULL NULL
张三 2007 7
李四 NULL NULL
王五 NULL NULL
*/