Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SELECT

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-10-10 : 06:53:54
Hello,

I have 4 tables related as follows:
[A] > Aid, ...
[B] > Bid, Aid, ...
[C] > Cid, ...
[CinB] > CinBid, Bid, Cid, ...

I need, given an Aid, to get the unique C records related with A:

SELECT x.*
FROM dbo.A AS a
INNER JOIN dbo.B AS b
ON a.Aid = b.Aid
INNER JOIN (
SELECT cinb.Bid, cinb.Cid
FROM dbo.CinB cinb
INNER JOIN dbo.C AS c
ON c.Cid = cinb.Cid) AS x
ON b.Bid = x.Bid
WHERE a.Aid = @Aid

This code is no working because I don't get the unique C records.
For example:
- A1 is related to B1 and B2
- B1 is related to C1
- B2 is related to C1

Then I get:
A1 (B1) C1
A1 (B2) C1

I want to get only:
A1 C1

So unique C records and not duplicated.

Thanks,
Miguel

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-10-10 : 06:57:26
The answer is here http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=90071
Put a DISTINCT over the column you want.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-10-10 : 08:47:23
Hi,

I solved it. Not sure if it is the best way but it is working:

declare @B table (Bid int identity, description varchar(50))
declare @P table (Pid int identity, Bid int, description varchar(50))
declare @T table (Tid int identity, description varchar(50))
declare @TinP table (TinPid int identity, Tid int, Pid int)
insert into @B (description) select 'B1'
insert into @B (description) select 'B2'
insert into @P (description, Bid) select 'P1', 1
insert into @P (description, Bid) select 'P2', 1
insert into @P (description, Bid) select 'P3', 2
insert into @T (description) select 'T1'
insert into @T (description) select 'T2'
insert into @T (description) select 'T3'
insert into @TinP (Tid, Pid) select 1, 1
insert into @TinP (Tid, Pid) select 1, 2
insert into @TinP (Tid, Pid) select 2, 2
insert into @TinP (Tid, Pid) select 3, 3
select * from @B
select * from @P
select * from @T
select * from @TinP

select t.*
from @T t
where exists
(
select * from @P p
inner join @TinP tp
on tp.Pid=p.Pid and tp.Tid=t.Tid
where p.Bid = @Bid
)

Thanks,
Miguel
Go to Top of Page
   

- Advertisement -