根据其他查询选择随机数据库行

时间:2011-10-25 16:22:41

标签: sql-server sql-server-2005

对于内部控制,我们希望为多种发票类型和区域中的每一种选择单个随机发票。

这是获取一组不同的发票类型和区域的SQL

  select InvoiceType,RegionID 
  from Invoices 
  group by InvoiceType, RegionID 

对于返回的每一行,我需要使用InvoiceTypeRegionID获取随机行。这就是我提取随机行的方式:

SELECT top 1 
   CustomerID
  ,InvoiceNum
  ,Name
  FROM Invoices
  JOIN Customers on Customers.CustomerID=Invoices.CustomerID
 where InvoiceType=X and RegionID=Y
ORDER BY NEWID

但是我不知道第一个语句返回时如何运行这个select语句foreach()行。我可以通过编程方式进行,但我更喜欢只使用存储过程的选项,因为此查询不需要程序。

1 个答案:

答案 0 :(得分:2)

WITH cteInvoices AS (
    SELECT CustomerID, InvoiceNum, Name,
           ROW_NUMBER() OVER(PARTITION BY InvoiceType, RegionID ORDER BY NEWID()) AS RowNum
        FROM Invoices
)
SELECT c.CustomerID, c.InvoiceNum, c.Name
    FROM cteInvoices c
    WHERE c.RowNum = 1;