0

I have this table:

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

I want to select 1 random record in a group of 5 and place it in a different table. Is it possible?

For example, for first group(ID 1 to 5) I want to select any ID. Similarly in the second group(6 to 10), I have to select any ID.

user3325141
  • 79
  • 1
  • 1
  • 6
  • #winces# - Lets see, `State` has the following problems - Two different spellings of `'Arizona'` (one is capitalized), `'North Dakota'` lacks the separating space... what are the rest of your entries like? If possible, you should have something like a `State` table that you can foreign-key link to. – Clockwork-Muse Mar 26 '14 at 00:57

3 Answers3

1

Try something like this

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

See also the question, Select first row in each GROUP BY group?

Community
  • 1
  • 1
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
1

This query will randomly select 1 record for every 5 IDs, no matter how many records are in @YourTable. The assumption is that each record has a consecutive 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
Ron Smith
  • 3,241
  • 1
  • 13
  • 16
0

Here i am getting the top 1 record from the table just to pick the record from the 1- 5 records. I hope this helps. i have set the counter to 10 , you may set it to the max count you want and increment i have set is 5. you can change it for your wish.

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;
Mahesh Sambu
  • 349
  • 2
  • 15