Skip to content
Advertisement

How do I create a table from distinct values in another table?

I have a table of orders that I want to create a table of possible customers from. I would like to take the distinct names in the customer record and create new table in the same SQL database with and assign it an auto incrementing Id as the PK. How can I script this?

Id | Name   | Customer
-------------------------
1    Apple      Nancy
2    Cucumber   Bob
3    Apple      Nancy

Advertisement

Answer

IF(OBJECT_ID('tempdb..#TEST_HappyFriday') IS NOT NULL) 
BEGIN
    DROP TABLE #TEST_HappyFriday
END

CREATE TABLE #TEST_HappyFriday
(
   Id INT IDENTITY(1,1) PRIMARY KEY,
   Customer VARCHAR(50)
)


INSERT INTO #TEST_HappyFriday
SELECT DISTINCT Customer FROM [Orders]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement