简体   繁体   English

随机选择多条记录

[英]Randomly Selecting Multiple Records

I have a table with both Male & Female genders (PK (Id), PersonsName, IsMale).我有一个包含男性和女性性别(PK(Id)、PersonsName、IsMale)的表格。 I wish to get a random name but for both genders.我希望获得一个随机名称,但适用于两种性别。 Example:例子:

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '1' 
Order by NewID()

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '0' 
Order by NewID()

How can I combine those statements so I return 2 records (1 male and 1 female name) from the one SQL statement?如何组合这些语句,以便从一个 SQL 语句返回 2 条记录(1 个男性和 1 个女性姓名)?

I have seen on here in the past that someone just separated the two statements in the same SQL query, like so:过去我在这里看到有人只是将同一 SQL 查询中的两个语句分开,如下所示:

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '1' 
Order by NewID();

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '0' 
Order by NewID()

Each time the code is run I wish to have two totally random names and not two records of the same gender so I can populate the dataset and bind it to a ListView control.每次运行代码时,我希望有两个完全随机的名称,而不是两个相同性别的记录,以便我可以填充数据集并将其绑定到 ListView 控件。 I just need the SQL statement我只需要 SQL 语句

What you are looking for is the UNION keyword您正在寻找的是UNION关键字

select PersonsName from (Select TOP 1 PersonsName From MyTable Where IsMale = '1' Order by NewID()) a
UNION ALL
Select PersonsName from (Select TOP 1 PersonsName From MyTable Where IsMale = '0' Order by NewID()) b

This will return 1 result set with 2 rows.这将返回 1 个包含 2 行的结果集。

You can also use Row_Number() and the WITH TIES clause.您还可以使用 Row_Number() 和 WITH TIES 子句。 This will return one of each.这将返回其中之一。

Select Top 1 with Ties *
 From  YourTable
 Order By Row_Number() over (Partition By IsMale Order by NewID())

On a side-note.顺便提一下。 Top 4 will give you two of each前 4 名每人送两个

Use union keyword for avoiding same duplicates records.使用 union 关键字来避免相同的重复记录。 Union is a keyword, use for writing two sql query which return same type of records with same number of columns(columns names can be differ but alias should me same for two queries). Union 是一个关键字,用于编写两个 sql 查询,它们返回具有相同列数的相同类型的记录(列名可以不同,但​​两个查询的别名应该相同)。

Select Top 1 PersonsName From MyTable Where IsMale = '1' Order by NewID() union Select Top 1 PersonsName From MyTable Where IsMale = '0' Order by NewID()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM