假设我有下表:
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选择随机行,我可以这样做
select top 3
tbble.unitid,tbble.transtatus, tbble.currency
from tbble
order by newid()但是,由于一些行共享相同的unitid (如果是这样的话),我想拉出与此unitid关联的所有行
因此,查询将返回:(以防随机行只有一行对应于此unitid)
unitid | transtatus | currency
---------------------------------------
1024393230 | not_started | GBp - Pence
1024401371 | not_started | GBp - Pence
1024403375 | in_progress | GBp - Pence或者:(如果有两行与此unitid相关联)
1024397398 | in_progress | GBp - Pence
1024397398 | not_started | USd - Cent
1024401371 | not_started | GBp - Pence
1024403375 | in_progress | GBp - Pence我真的不确定我如何才能做到这一点。也许首先计算单标出现的数量,然后如果计数大于1,则将其添加到初始随机样本中?
发布于 2016-09-07 18:33:54
我认为这就完成了您想要的,即三个随机的单元I及其所有行:
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发布于 2016-09-07 18:01:37
也许您可以使用子查询分两步工作:首先用子查询选择一些随机的unitid,然后对每个unitid选择表中具有相同use的整行。它应该看起来像这样:
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())发布于 2016-09-07 18:08:49
应该使用WITH TIES子句来获取匹配的行
select top 3 WITH TIES *
tbble.unitid,tbble.transtatus, tbble.currency
from tbble
order by newid()https://stackoverflow.com/questions/39366638
复制相似问题