Select unique random rows from SQL Server table but always duplicates

早过忘川 提交于 2019-12-04 06:28:10

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24844040/select-unique-random-rows-from-sql-server-table-but-always-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!