我想将表连接到两个表,并希望得到以下格式的结果,
ID Name1 Name2 StatusOfName2Yearwise Year
我所尝试的是,
select t1.ID, t1.Name as 'Name1', t1a.Name as 'Name2', isnull(t2.Status,'N') as 'StatusOfName2Yearwise',Year
from
table_1 t1, table_1 t1a
LEFT JOIN table_3 t3 on t1a.id=t3.f_id
LEFT JOIN table_2 t2 on t1a.ID=t2.id,
table_4 t4 LEFT JOIN table_2 t2a on t4.Year=t2a.Fyr
where
t1.ID=t3.f_id
group by
t1.ID, t1.Name, t1a.Name, t2.Status ,Year
order by
t1.Name
这个查询给出了Name2的状态,但它不是逐年的,我想要它的年份。如果有人知道,请帮忙..
添加我从查询中获得的输出数据
ID Name1 Name2 StatusOfName2Yearwise Year
22 George Julie C 2015
22 George Julie C 2016
22 George Julie C 2017
预期结果应如下所示,
ID Name1 Name2 StatusOfName2Yearwise Year
22 George Julie N 2015
22 George Julie N 2016
22 George Julie C 2017
答案 0 :(得分:0)
在不知道表格中的数据的情况下,我试图推断出其中的内容。
基于该测试数据,我构建了一个可以给出预期结果的SQL(Sql Server)。
桌面上的完整加入确保每年都会显示,即使表2中没有相应的Fyr。
对于测试,变量表的名称略有意义。
DECLARE @table_1_user TABLE (id int, Name varchar(8));
DECLARE @table_2_userstatus TABLE (id int, Status char(1), Fyr char(4));
DECLARE @table_3_userrelation TABLE (id int, f_id int);
DECLARE @table_4_year TABLE (Year char(4));
insert into @table_1_user values
(22,'George'),
(23,'Julie');
insert into @table_2_userstatus values
(22,'C','2016'),
(22,'X','2017'),
(23,'N','2016'),
(23,'C','2017');
insert into @table_3_userrelation values (22,23);
insert into @table_4_year values ('2015'),('2016'),('2017');
select distinct
t1a.id as Id1,
t1b.id as Id2,
t1a.Name as Name1,
t1b.Name as Name2,
isnull(t2b.Status,'N') as StatusOfName2Yearwise,
q.Year
from (
select * from @table_3_userrelation t3
full outer join @table_4_year t4 on (1=1)
) q
left join @table_1_user t1a on (q.id = t1a.id)
left join @table_1_user t1b on (q.f_id = t1b.id)
left join @table_2_userstatus t2b on (q.f_id = t2b.id and q.Year = t2b.Fyr)
order by t1a.Name, t1b.Name, q.Year;
这将得到以下结果:
Id1 Id2 Name1 Name2 StatusOfName2Yearwise Year
22 23 George Julie N 2015
22 23 George Julie N 2016
22 23 George Julie C 2017