我有这张桌子:
Name ID State
====== == ============
sarah 1 arizona
daniel 2 california
disney 3 Arizona
dee 4 wyoming
eee 5 texas
ape 6 oklahoma
eee 7 kansas
csdsd 8 iowa
dfsdf 9 utah
deep 10 northdakota
我想在一组5中选择1个随机记录并将其放在不同的表中。可能吗?
例如,对于第一组(ID 1到5),我想选择任何ID。同样在第二组(6到10)中,我必须选择任何ID。
答案 0 :(得分:1)
尝试这样的事情
insert dbo.bar ( Name, ID , State )
select t.Name , t.ID , t.State
from ( select * ,
rownum = row_number()
over ( partition by ID / 5 order by newid() )
from dbo.foo
) t
where r.rownum = 1
答案 1 :(得分:1)
无论@YourTable中有多少条记录,此查询将为每5个ID随机选择1条记录。假设每条记录都有一个连续的ID。
-- load test data
declare @YourTable table(Name varchar(10),ID int identity(1,1), [State] varchar(20))
insert into @YourTable(Name,[State])
values ('sarah','arizona'),
('daniel','california'),
('disney','Arizona'),
('dee','wyoming'),
('eee','texas'),
('ape','oklahoma'),
('eee','kansas'),
('csdsd','iowa'),
('dfsdf','utah'),
('deep','northdakota')
-- randomly select 1 record from every 5 IDs
select ID,Name,[State]
from (
select ID,Name,[State],
row_number() over(partition by (ID-1)/5 order by newid()) rnd
from @YourTable
) r
where rnd = 1
答案 2 :(得分:0)
在这里,我从表中获得前1条记录,只是为了从1-5条记录中选择记录。我希望这有帮助。我已将计数器设置为10,您可以将其设置为您想要的最大计数,并且我设置的增量为5.您可以根据需要更改它。
DECLARE @counter smallint;
SET @counter = 1;
WHILE @counter < 10
BEGIN
INSERT INTO NEWTABLE --- your destination table
( NAME, ID, STATE)
SELECT Top 1 * from yourtable where id between @counter and @counter + 5
SET @counter = @counter + 5
END;