首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有重复项的SQL随机样表

具有重复项的SQL随机样表
EN

Stack Overflow用户
提问于 2016-09-07 17:51:30
回答 3查看 108关注 0票数 2

假设我有下表:

代码语言:javascript
运行
复制
       unitid  |  transtatus |   currency
    ---------------------------------------
    1024393230 | not_started |  GBp - Pence
    1024397398 | in_progress |  GBp - Pence
    1024397398 | not_started |  USd - Cent
    1024397408 | not_started |  GBp - Pence
    1024397408 | not_started |  EUR
    1024401371 | not_started |  GBp - Pence
    1024403375 | in_progress |  GBp - Pence

我想为QC选择随机行,我可以这样做

代码语言:javascript
运行
复制
select top 3  
tbble.unitid,tbble.transtatus, tbble.currency
 from tbble
order by newid()

但是,由于一些行共享相同的unitid (如果是这样的话),我想拉出与此unitid关联的所有行

因此,查询将返回:(以防随机行只有一行对应于此unitid)

代码语言:javascript
运行
复制
      unitid   | transtatus  |  currency
    ---------------------------------------
    1024393230 | not_started | GBp - Pence
    1024401371 | not_started | GBp - Pence
    1024403375 | in_progress | GBp - Pence

或者:(如果有两行与此unitid相关联)

代码语言:javascript
运行
复制
    1024397398 | in_progress | GBp - Pence
    1024397398 | not_started | USd - Cent
    1024401371 | not_started | GBp - Pence
    1024403375 | in_progress | GBp - Pence

我真的不确定我如何才能做到这一点。也许首先计算单标出现的数量,然后如果计数大于1,则将其添加到初始随机样本中?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-09-07 18:33:54

我认为这就完成了您想要的,即三个随机的单元I及其所有行:

代码语言:javascript
运行
复制
select t.*
from tbble t join
     (select top 3 t.unitid
      from (select distinct t.unitid from tbble t) t
      order by newid()
     ) tt
     on t.unitid = tt.unitid
票数 1
EN

Stack Overflow用户

发布于 2016-09-07 18:01:37

也许您可以使用子查询分两步工作:首先用子查询选择一些随机的unitid,然后对每个unitid选择表中具有相同use的整行。它应该看起来像这样:

代码语言:javascript
运行
复制
select tbble.unitid, tbble.transtatus, tbble.currency
from tbble
where tbble.unitid in (select top 3  
tbble.unitid as randomunitid
 from tbble
order by newid())
票数 2
EN

Stack Overflow用户

发布于 2016-09-07 18:08:49

应该使用WITH TIES子句来获取匹配的行

代码语言:javascript
运行
复制
select top 3   WITH TIES *
tbble.unitid,tbble.transtatus, tbble.currency
 from tbble
order by newid()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39366638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档