简体   繁体   中英

Join Table and maintain same amount of rows based on value in a column

I have a query:

SELECT t.USER_ID, c.CODE 
FROM TRANSACTIONS t 
INNER JOIN USER u ON t.USER_ID = u.USER_ID 
INNER JOIN COMPANY c ON c.CODE = u.CODE

which returns this result set:

USER ID     CODE
-----------------
01          100
02          100
03          100
03          120

Then I have table INTERACTIONS (for example), which lists every interaction with code:

CODE     INTERACTION     WORKED_YN
-----------------------------------
100      Sample 01       Y
100      Sample 02       Y
120      Sample 03       N
120      Sample 04       N
etc.

The CODE column values should always have the same outcome (ie. 100 will always be Y and 120 will always be N).

How do I join table INTERACTIONS without having every interaction, so that I can have the following output:

USER ID     CODE    WORKED_YN
-----------------------------
01          100     Y
02          100     Y
03          100     Y
03          120     N

Since you don't need INTERACTIONS.INTERACTION column in your result set you can just subquery your INTERACTIONS table to get distinct records omitting that column:

SELECT t.USER_ID, c.CODE 
FROM (SELECT DISTINCT CODE, WORKED_YN, USER_ID FROM TRANSACTIONS) t 
INNER JOIN USER u ON t.USER_ID = u.USER_ID 
INNER JOIN COMPANY c ON c.CODE = u.CODE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM