user3856495
user3856495

Reputation: 3

Select unique random rows from SQL Server table but always duplicates

i am not the best with sql but i try my best to get my Problems done. I have a table "just" which is filled with Columns ( ID (PK, Identity), Char, Serv , Random ) . Now i want to select a random row from this table and insert it into the Table "f_WinGet". So far all my Procedures take this Step fine , but i always get Duplicates in the second table.

First table : 84 rows Second table: needed 35 random out of 84.

I have tried many other ways but i always get the same result. All my Procedure for random are binded to a Button i a C# Programm. All is working fine so far , but i always have some Duplicates of Rows in my Table.

 INSERT INTO f_TWinGet 
     SELECT TOP 1 Percent Char, Serv, Random
          FROM ( select distinct  Char, Serv, Random from dbo.just) as derived1 
               ORDER BY CHECKSUM(NEWID())

It would be nice , if anyone hase an Idea how i can fix my Problem. I am still trying , but all what i get are always the same result.

Upvotes: 0

Views: 1322

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270421

It you want to insert 35 rows, do it all at once:

INSERT INTO f_TWinGet(char, serv, random)
     SELECT TOP 35 Char, Serv, Random
     FROM (select distinct  Char, Serv, Random
           from dbo.just
          ) derived1 
     ORDER BY CHECKSUM(NEWID());

If you really want to do them one at a time, I would suggest using not exists:

INSERT INTO f_TWinGet(char, serv, random)
     SELECT TOP 1 Char, Serv, Random
     FROM (select distinct  Char, Serv, Random
           from dbo.just
          ) d
    WHERE not exists (select 1 from f_TWinGet f where t.char = f.char and t.serv = f.serv and t.random = f.random)
     ORDER BY CHECKSUM(NEWID());

Note that char is a reserved word, so it should be in square braces. I am leaving the names you have have them in your query.

Upvotes: 1

bruno
bruno

Reputation: 2882

With a table as small as yours you can use something like:

INSERT INTO f_TWinGet
SELECT TOP 1 j.Char, j.Serv, j.Random
FROM dbo.just j 
LEFT JOIN f_TWinGet f
ON f.Char = j.Char
AND j.Serv = f.Serv
AND j.Random = f.Random
WHERE f.Char IS NULL
ORDER BY NEWID()

This way making sure that the values you're trying to insert is not on the final table.

Upvotes: 0

Related Questions