0

I have two tables - table1 and table2. Both contains two columns - rollnum,name. Now I wants to select all rows from table1 and randomly 5rows from table2. I have written like this

select rollnum,name from table1 union (select top 5 rollnum,name from table2 order by NEWID()) 

but it shows an error ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator. please help . I think the mistake is at NEWID(). here rollnum is primary key

4

2 回答 2

1

The problem is with the brackets. Try this instead

 select rollnum,name from table1 
 union 
 select * from (select top 5 rollnum,name from table2 order by NEWID())  t

If you could have duplicate entries you may want to consider a union all instead of union

于 2013-10-10T07:04:00.953 回答
-1

Try This..

SELECT  rollnum AS 'NewID' ,
        name
FROM    table1
UNION
SELECT TOP 5
       rollnum ,
       name
FROM    table2
ORDER BY NewID

NEWID() is a function which assign a value to a variable declared as the uniqueidentifier data type

于 2013-10-10T06:42:07.047 回答