【问题标题】:Pulling random records for each pair of values an another table SQL将每对值的随机记录拉到另一个表 SQL 中
【发布时间】:2022-01-11 07:20:18
【问题描述】:

我希望为表 2 中的每个班级-教师对在表 1 中随机抽取 2 个学生姓名。我研究过使用

表 1

Class Teacher
Math Mr. Smith
Math Mrs. Kim
Science Mr. Smith
Science Mrs. Kim

表 2

Student
Matt
Jess
Tom
Sally
Rod
Nikki

最后的例子

Class Teacher Student
Math Mr. Smith Matt
Math Mr. Smith Sally
Math Mrs. Kim Nikki
Math Mrs. Kim Rod
Science Mr. Smith Matt
Science Mr. Smith Jess
Science Mrs. Kim Tom
Science Mrs. Kim Rod

【问题讨论】:

  • 您真的需要它们是随机的,还是只有任何个学生会这样做?
  • 它们必须是随机的

标签: sql database postgresql


【解决方案1】:

您可以使用RANDOM() 对行进行随机排序,然后选择前两个。

例如:

select
  a.*, x.*
from table1 a,
lateral (
  select  *
  from table2
  order by length(a.class) * 0 + random()
  limit 2
) x

结果:

 class    teacher    student 
 -------- ---------- ------- 
 Math     Mr. Smith  Matt    
 Math     Mr. Smith  Jess    
 Math     Mrs. Kim   Nikki   
 Math     Mrs. Kim   Rod     
 Science  Mr. Smith  Rod     
 Science  Mr. Smith  Jess    
 Science  Mrs. Kim   Tom     
 Science  Mrs. Kim   Jess    

请参阅DB Fiddle 的运行示例。请注意,每次运行查询时结果都会发生变化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多