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

求一个简单的sql语句 关于两表关联的问题
T1
id       name           Date1                     num
1         user1         2007-02-01             3
2         user1         2007-02-02             6
3         user2         2007-02-01             7

T2
id             Date2  
1               2007-02-01
2               2007-02-02
3               2007-02-03


现在我想要两个表关联起来做一个查询
(根据T2中的记录)T1中的User1   在2007-02-03这一天没有记录产生,因此我想把查询的结果增加一条   “user1         2007-02-03             0”

查询结果如下:

name           Date1                     num
user1         2007-02-01             3
user1         2007-02-02             6
user1         2007-02-03             0
user2         2007-02-01             7
user2         2007-02-02             0
user2         2007-02-03             0

谢谢

------解决方案--------------------
declare @a table(id int, name varchar(10),Date1 smalldatetime, num int)
insert @a select 1 , 'user1 ', '2007-02-01 ', 3
union all select 2 , 'user1 ', '2007-02-02 ', 6
union all select 3 , 'user2 ', '2007-02-01 ', 7

declare @b table(id int, Date2 smalldatetime)
insert @b select 1 , '2007-02-01 '
union all select 2 , '2007-02-02 '
union all select 3 , '2007-02-03 '
union all select 4 , '2007-02-04 '

select name,x date,max(num) num
from
(select name,case when date1=date2 then date1 else date2 end x,num =case when date1=date2 then num else 0 end from @a a , @b b )aa
group by name,x order by name


------解决方案--------------------
select *,isnull((select num from t1 where t1.name=a.name and t1.date1=b.date1),0) as num from (select distinct name from t1) a,(select distinct date2 as date1 from t2) b order by name,date1