Today a group of brothers asked a question, said there is a table, there are a lot of data in the table, which has a field type, you want to randomly remove 10 records from the table, including 5 type=1 another 5 type=0, such as the following image:
I think, this is not simple, according to the requirements, each take top 5, since it is random take, then the order by NEWID () is three, and then all the data union up. So I immediately gave the answer:
select top 5 * from xxx where type=1 order by newid()
union
select top 5 * from xxx where type=0 order by newid()
But the brother said wrong, grammar is wrong, I at first glance, seems to have no problems, so let him give me the definition of the table, I try on this machine, the table definition is:
CREATE TABLE [dbo]. [Question] (
[ID] [int] IDENTITY (1,1) not NULL,
[Question] [varchar] () not NULL,
[Answer] [varchar] () not NULL,
[Type] [Bit] Not NULL,
CONSTRAINT [pk_question] PRIMARY KEY CLUSTERED
(
[ID] ASC
With (pad_index = off, statistics_norecompute = off, Ignore_dup_key = off, allow_row_locks = ON, allow_page _locks = on) on [PRIMARY]
) on [PRIMARY]
So my statement into the SSMS, the result system is really an error: Incorrect syntax near the keyword ' order '.
What's going on? It doesn't look like a problem. So I do it alone.
select top 5 * from dbo.Question
where [type]=1
ORDER BY newid()