Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Select unique random rows from the SQL Server table but still duplicates

$
0
0

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.

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.


Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles