如何从另一个 table 中的不同值创建一个 table?
How do I create a table from distinct values in another table?
我有 table 个 orders
个,我想从中创建 table 个可能的客户。我想在客户记录中使用不同的名称并在同一个 SQL 数据库中创建新的 table 并为其分配一个自动递增的 Id 作为 PK。我该如何编写脚本?
Id | Name | Customer
-------------------------
1 Apple Nancy
2 Cucumber Bob
3 Apple Nancy
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]
您可以使用select into
/* drop table if exists PossibleCustomers */
select Row_Number() over (order by Customer) Id, Customer
into PossibleCustomers
from (select distinct Customer from Orders)o
我有 table 个 orders
个,我想从中创建 table 个可能的客户。我想在客户记录中使用不同的名称并在同一个 SQL 数据库中创建新的 table 并为其分配一个自动递增的 Id 作为 PK。我该如何编写脚本?
Id | Name | Customer
-------------------------
1 Apple Nancy
2 Cucumber Bob
3 Apple Nancy
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]
您可以使用select into
/* drop table if exists PossibleCustomers */
select Row_Number() over (order by Customer) Id, Customer
into PossibleCustomers
from (select distinct Customer from Orders)o