在组中选择N个随机行

时间:2014-01-09 08:22:44

标签: sql sql-server

请注意以下SQL查询获得12个随机行。

SELECT TOP 12 ExportSystem.sysID, ExportSystem.sysNo, ExportSystem.sysName, Document.docArchiveNo FROM ExportSystem
INNER JOIN Customer ON ExportSystem.sysNo = Customer.expSysNr
INNER JOIN Department ON Customer.cusID = Department.cusID
INNER JOIN Level ON Level.levParentID = Department.levRootID
INNER JOIN Document ON Document.levID = Level.levID
GROUP BY ExportSystem.sysID, ExportSystem.sysNo, ExportSystem.sysName, Document.docArchiveNo
ORDER BY newid()

结果

SystemName  ArchiveNo
RR  31676981
AA  28741154
AA  30435868
AA  29665408
AA 28116900
BB  31114199
RR  29080695
AA  29903701
VV  31890130
BB  29898481
BB  30892927
AA  30545346

我尝试了很多东西,但还没弄清楚如何为每个组获取相同数量的行。目前有两个RR,六个AA,三个BB和一个VV。如何在每个SystemName组中获得4行。

1 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER排名函数PARTITION BY Systemname来执行此操作:

WITH CTE
AS
(
   SELECT 
     ExportSystem.sysID, 
     ExportSystem.sysNo, 
     ExportSystem.sysName, 
     Document.docArchiveNo,
     ROW_NUMBER() OVER(PARTITION BY ExportSystem.sysName 
                       ORDER BY newid()) AS RN 
  FROM ExportSystem
  INNER JOIN Customer   ON ExportSystem.sysNo = Customer.expSysNr
  INNER JOIN Department ON Customer.cusID     = Department.cusID
  INNER JOIN Level      ON Level.levParentID  = Department.levRootID
  INNER JOIN Document   ON Document.levID     = Level.levID
)
SELECT 
  sysID, 
  sysNo, 
  sysName, 
  docArchiveNo
FROM CTE
WHERE RN <= 4;

请注意:在原始查询中选择GROUP BY中的相同列无效,无需使用GROUP BY。将其删除并改为使用DISTINCT