0

I am using SQL Server 2008 and have the following scenario:

I have Table a with fields id and groupId.

I have Table b with fields id and groupId also.

The rule in Table b, is that:

If a.id = 0, then a.groupId = b.groupId
Else a.id = b.id (in which case a.groupId = 0)

The 2 tables are also linked by agrId such that a.agrId = b.agrId

How can I join these tables, whilst satisfying the rule above?

Update: Apologies for the lack of clarity, I have updated the rule and added my attempt below:

select * from a
inner join b
on a.agrId = b.agrId
where (
    (b.id > '0' and b.groupId = '0') 
    or
    (b.groupId > '0' and b.id = '0')
  )
Devan Somaia
  • 645
  • 1
  • 8
  • 21

3 Answers3

2

Try this

SELECT *
FROM TableA A
INNER JOIN TableB B
    ON (B.ID = 0 AND A.groupId = B.groupId)
        OR (B.groupId = 0 AND A.id = B.id)
user2321864
  • 2,207
  • 5
  • 25
  • 35
  • can u please edit anything in your answer .. i misunderstood the answer and downvoted but now its since more then 5 min i cannot rollback it – Dhaval Jun 12 '14 at 06:16
0

Al it needs is an expression that evaluates to true or false, to indicate if these two rows should be joined. So based on what you say, this would be the join condition:

select  *
from    tA a 
        inner join tB b 
            on (a.id = 0 and a.groupid = b.groupid) 
            or (a.groupid = 0 and a.id = b.id)
gjvdkamp
  • 9,929
  • 3
  • 38
  • 46
0

Try this:

SELECT *
FROM   a INNER JOIN
       b ON a.agrId = b.agrId
WHERE  (b.id = '0' AND b.groupId = a.groupId) 
       or
       (b.groupId = '0' AND b.id = b.id)
Jesuraja
  • 3,774
  • 4
  • 24
  • 48