添加名称列并为每个名称分配5个会话ID

时间:2018-11-07 21:10:44

标签: sql-server tsql

我下面有一个名为客户-DDL的表

 SELECT
  @Report1WeeklyBody1 =
(
  SELECT
    TOP 20
    TD = sessionID
   ,TD = CONVERT(NVARCHAR(500), customerid)
   ,TD = @URL + sessionID
  FROM
    (
      SELECT
        DISTINCT
        sessionID
       ,customerID
      FROM
        customers
      WHERE
        CONVERT(DATETIME, dateofevent, 111) BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), '04:00:00:001') AND DATEADD(d, DATEDIFF(d, -1, GETDATE()), '03:59:59:999')
      GROUP BY
        sessionID
       ,customerid
    ) AS A
  ORDER BY
    NEWID()
  FOR XML RAW('tr'), ELEMENTS
);

现在我有一个存储过程,可以每天提取HTML表格格式的前20个会话ID,用于邮寄目的

{{1}}

现在,我必须修改上面的存储过程,以添加一个新的列名称,并为以下名称分别分配5个不同的会话ID:

  

Max,Allen,Amy,Josh,Suzier

这样,每天可以发送带有25个会话ID的五个名称的整个HTML表

有人可以帮忙吗?

我正在使用SQL Server 2017

1 个答案:

答案 0 :(得分:1)

首先,将top子句移至内部选择并将行数更改为25。然后在内部选择中添加新列以显示行号。在外部选择行号,然后根据范围(1..5、6..10等)返回不同的人。

最后,您的select语句应如下所示:

SELECT
  @Report1WeeklyBody1 =
(
  SELECT
    TD = sessionID
   ,TD = CONVERT(NVARCHAR(500), customerid)
   ,TD = @URL + sessionID
   ,TD = case when RowNo <= 5 then 'Max'
            when RowNo <= 10 then 'Allen'
            when RowNo <= 15 then 'Amy'
            when RowNo <= 20 then 'Josh'
            when RowNo <= 25 then 'Suzier' end
  FROM
    (
      SELECT
        DISTINCT TOP 25
        sessionID
       ,customerID
       , ROW_NUMBER() over(order by newid()) as RowNo
      FROM
        @customers
      WHERE
        CONVERT(DATETIME, dateofevent, 111) BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), '04:00:00:001') AND DATEADD(d, DATEDIFF(d, -1, GETDATE()), '03:59:59:999')
      GROUP BY
        sessionID
       ,customerid
    ) AS A
  ORDER BY
    NEWID()
  FOR XML RAW('tr'), ELEMENTS
);