Using SQL Server, I have a table RoleMembership
:
Id | Username | RoleId |
---|---|---|
1 | bobby | 1 |
2 | bobby | 2 |
3 | bobby | 3 |
4 | suzie | 3 |
5 | suzie | 4 |
6 | suzie | 5 |
7 | billy | 1 |
8 | billy | 7 |
etc.
I want to create a new Usermember
table with a row for each distinct value for the RoleMembership.Username
column, alone with some ID and date columns.
CREATE TABLE [access].[Usermember]
(
[Id] [bigint] NOT NULL,
[Username] [varchar](256) NOT NULL,
[CreatedAt] [datetime] NOT NULL
)
I want to copy the unique usernames such that the table will be as follows:
Id | Username | CreatedAt |
---|---|---|
1 | bobby | 05-13-23 |
2 | suzie | 05-13-23 |
3 | billy | 05-13-23 |
How can I do an insert into select distinct to copy unique Usernames into a row in this new table?
I've tried something like this:
INSERT INTO access.Usermember (Id, Username, CreatedAt)
SELECT
dbo.NextId('Usermember') + ROW_NUMBER() OVER (ORDER BY Id ASC),
(SELECT DISTINCT MemberName
FROM access.RoleMembership), GETDATE()
But the syntax isn't quite right.