2

自 2012 年 10 月 1 日以来,我每天尝试选择 50 个随机文件。例如:

  • 10 月 1 日 = 50 个文件
  • 10 月 2 日 = 50 个文件
  • 10 月 3 日 = 50 个文件
  • 等等……今天

到目前为止,我每天可以选择 1 个文件,但我需要 50 个。而且我需要它们是随机的

DECLARE @DaysBack AS INT
SET @DaysBack = -25


    SET NOCOUNT ON;

    SELECT FileDate, MAX(FileName)  FROM (
    SELECT 
    CONVERT(VARCHAR(10),DATEADD(second,actiondate, CAST('1970-01-01 00:00:00' AS datetime)), 101) AS FileDate

    ,'\\directory\' + filename AS FileName
    FROM   Tableq q
    JOIN tablec c
    on  q.projectid = c.projectid
           AND actiondate >= Datediff(s, '19700101 00:00:00:000',
                             Dateadd(DAY, @DaysBack, Getutcdate()))


    ) x

    GROUP BY FileDate
    ORDER  BY FileDate 
4

3 回答 3

4

我目前无权访问 SQL Server 实例(或 SQL Fiddle)。但这应该给每个 actiondate 一个随机的 id ...

  • ROW_NUMBER() OVER (PARTITION BY actiondate ORDER BY NEWID())

这意味着以下将在每个 actiondate 中随机选择 50 个项目...

DECLARE @DaysBack AS INT
SET @DaysBack = -25

SET NOCOUNT ON;

SELECT
  FileDate, FileName
FROM
(
  SELECT 
    DATEADD(DAY, actiondate / 86400, '19700101') AS FileDate,
    '\\\\directory\\' + filename AS FileName,
    ROW_NUMBER() OVER (PARTITION BY actiondate / 86400 ORDER BY NEWID()) AS random_daily_id
FROM
  Tableq q
JOIN
  tablec c
    ON  q.projectid = c.projectid
    AND actiondate >= Datediff(s, '19700101', Dateadd(DAY, @DaysBack, Getutcdate()))
) x
WHERE
  random_daily_id <= 50
ORDER BY
  FileDate 
于 2012-10-25T13:33:02.963 回答
0

假设您使用的是 SQL Server 2005 或更高版本,您可以使用排名函数来执行此操作:

SELECT FileDate, MAX(FileName)
FROM (select x.*,
             ROW_NUMBER() over (partition by FileDate order by newid()) as seqnum
      from (SELECT CONVERT(VARCHAR(10),DATEADD(second,actiondate, CAST('1970-01-01 00:00:00' AS datetime)), 101
                          ) AS FileDate,
                   '\\directory\' + filename AS FileName
            FROM   Tableq q JOIN
                   tablec c
                   on  q.projectid = c.projectid and
                       actiondate >= Datediff(s, '19700101 00:00:00:000',
                                     Dateadd(DAY, @DaysBack, Getutcdate()))
           ) x
     ) x
where seqnum <= 50
ORDER  BY FileDate

这用于row_number()为每个日期的文件添加一个序列号,编号随机分配。然后它会为每个日期选择前 50 名。

于 2012-10-25T13:34:27.810 回答
0

强烈建议您不要实施任何随机提取数据库端。我在一个项目中也有类似的需求,但最终我将随机化逻辑移到了业务端。

于 2012-10-25T13:35:35.533 回答