嗨,我有3个表,我想加入他们得到一个愿望表。我尝试了分组和临时表选项来获得所需的表,但没有帮助。我想避免从另一个表中的一个表中的每个值的每个实例重复。当与表加入时,避免重复每个实例的行
表1客户表:
CstId CstDetails CstType
---------- --------------- ------------
1 address 1 1
2 address 2 1
3 address 3 1
4 address 4 2
5 address 5 2
表2客户关系:
CstId CstGroupId
---------- ----------------
1 4 (this is same as CustomerId)
2 5 (this is same as CustomerId)
3 4 (this is same as CustomerId)
表3顾客注:
CstId NotesId NoteTxt
----------- --------- ---------
1 1 note11
1 2 note12
1 3 note13
3 1 note31
4 1 note41
4 2 note42
4 3 note43
4 4 note44
4 5 note45
现在我想的结果是在下述格式
Table result:
(NoteId) (Notetxt) (NoteId) (Notetxt)
CstId CstDetails CstGroupId CstNoteId CstNote CstGroupNoteId CstGroupNote
1 address1 4 1 note11 1 note41
1 address1 4 2 note12 2 note42
1 address1 4 3 note13 3 note43
1 address1 4 null null 4 note44
1 address1 4 null null 5 note45
但我正在为所有CstNote重复CstGroupNote,我试图避免。
有没有办法实现这个结果?
下面是我使用的代码:
select c.cstid, c.cstdetails, cn.cstnotesid, cn.cstnotetxt
insert into temp1
from customer c
left outer join customernotes cn
on c.cstid = cn.cstid
where c.customertypeid = 1
select cr.cstid, cr.cstgroupid, cn.cstgroupnoteid, cn.cstnotetxt
insert into temp2
from customerrelationship cr
left outer join customernotes cn
on cr.cstgroupid = cn.customerid
select t1.cstid, t1.cstdetails, t1.cstnotesid, t1.cstnotetxt, t2.cstgroupnoteid, t2.cstnotetext
from temp1 t1
left outer join t2
on t1.cstid = t2.cstid
到目前为止您的查询是什么? – dotjoe 2013-02-20 15:56:57
我已创建2个临时表之一来获得customernotes和第二得到groupnotes,然后我加入都与左外临时表联接根据客户ID下面 – user2091818 2013-02-20 16:01:01
是我使用的代码:选择c.cstid,c.cstdetails,CN。 cstnotesid,cn.cstnotetxt 从客户C插入temp1中 \t左外连接CN \t \t customernotes上c.cstid = cn.cstid 其中c.customertypeid = 1个 选择cr.cstid,cr.cstgroupid,CN .cstgroupnoteid,cn.cstnotetxt 从customerrelationship插入到temp2 cr \t左外连接自定义ernotes CN \t \t上cr.cstgroupid = cn.customerid 选择t1.cstid,t1.cstdetails,t1.cstnotesid,t1.cstnotetxt,t2.cstgroupnoteid,t2.cstnotetext 从T1的temp1 \t左外连接T2 \t \t on t1.cstid = t2.cstid – user2091818 2013-02-20 16:11:56