Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

little help with some tsql

Tags:

sql

sql-server

Given following table:

rowId  AccountId  Organization1  Organization2
-----------------------------------------------
1      1          20             10
2      1          10             20
3      1          40             30
4      2          15             10
5      2          20             15
6      2          10             20

How do I identify the records where Organization2 doesn't exist in Organization1 for a particular account

for instance, in the given data above my results will be a single record which will be AccountId 1 because row3 organization2 value 30 doesn't exist in organization1 for that particular account.

like image 786
Rod Avatar asked Dec 29 '22 06:12

Rod


2 Answers

SELECT rowId, AccountId, Organization1, Organization2
FROM   yourTable yt
WHERE  NOT EXISTS (SELECT 1 FROM yourTable yt2 WHERE yt.AccountId = yt2.AccountId AND yt.Organization1 = yt2.Organization2)
like image 181
Andrew Avatar answered Jan 13 '23 06:01

Andrew


There are two possible interpretations of your question. The first (where the Organization1 and Organization2 columns are not equal) is trivial:

SELECT AccountID FROM Table WHERE Organization1 <> Organization2

But I suspect you're asking the slightly more difficult interpretation (where Organization2 does not appear in ANY Organization1 value for the same account):

SELECT AccountID From Table T1 WHERE Organization2 NOT IN 
  (SELECT Organization1 FROM Table T2 WHERE T2.AccountID = T1.AccountID)
like image 39
Larry Lustig Avatar answered Jan 13 '23 07:01

Larry Lustig