inner join select where x in y

Guido Jeuken 71 Reputation points
2021-02-03T11:51:45.02+00:00

Hello Community,
I have two tables that I need to combine.

table user
username | customerId
Guido | 1, 2, 3

table customer
customerID | customer name | email address
1 | customer1 | ******@customer1.de
2 | customer2 | ******@customer2.de
3 | customer3 | ******@customer1.de

I would now like to have the following output:
Guido | customer1 | ******@customer1.de
Guido | customer2 | ******@customer2.de
Guido | customer3 | ******@customer2.de

I've tried to build an inner join with "select where customer.customerID in user.customeriD" but this does not work.

Many thanks an best regards

Guido

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Vaibhav Chaudhari 38,916 Reputation points Volunteer Moderator
    2021-02-03T12:16:49.963+00:00

    Could you try below?

    CREATE TABLE [User] ([username] VARCHAR(5), [customerId] VARCHAR(100));
    
    INSERT INTO [User] ([username], [customerId])
    VALUES ('Guido', '1,2,3');
    
    CREATE TABLE Customer ([customerID] INT, [customer name] VARCHAR(9), [emailaddress] VARCHAR(22));
    
    INSERT INTO Customer ([customerID], [customer name], [emailaddress])
    VALUES (1, 'customer1', '******@customer1.de'), (2, 'customer2', '******@customer2.de'), (3, 'customer3', '******@customer1.de');
    
    SELECT username, c.[customer name], c.EmailAddress
    FROM [user]
    CROSS APPLY string_split(customerId, ',') AS u
    INNER JOIN Customer AS c ON u.value = c.customerID
    

    Please don't forget to Accept Answer and Up-vote if the response helped -- Vaibhav

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2021-02-03T12:19:03.593+00:00

    Which SQL Server version are you using? Since version 2016 we do have the STRING_SPLIT (Transact-SQL) function to achieve your requirements.

    Olaf


  2. EchoLiu-MSFT 14,621 Reputation points
    2021-02-04T07:26:31.007+00:00

    Glad your problem is solved.
    If you have any question, please feel free to let me know.

    Regards
    Echo

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.