SQL 查询 – 执行循环但使用变量数组

标签 sql arrays loops

这是我正在编写的代码示例

DECLARE @totlunch int = 0;
DECLARE @totbreak int = 0;
DECLARE @over int = 0;


SELECT @totlunch = SUM(CASE when [StatusKey] = 'at lunch' then StateDuration else 0 end),
        @totbreak = SUM(CASE when [StatusKey] = 'break' then StateDuration else 0 end) 
  FROM [I3_IC].[dbo].[AgentActivityLog]
  WHERE UserId in ('mdavila')
    AND StatusDateTime between '2014-08-28 00:00:00' AND '2014-08-28 23:59:59'
  --group by UserId

  print @totlunch;
  print @totbreak;

  if(@totlunch > 3600)BEGIN
    SET @over = @over + (@totlunch - 3600);
  END

  if(@totbreak > 1800)BEGIN
    SET @over = @over + (@totbreak - 1800);
  END

  print @over;  

我想为一组“UserId”(而不是 juat“mdavila”)执行此任务,但我不确定如何循环它,因为 SQL 查询似乎不支持数组。任何有关我如何完成这项任务的帮助将不胜感激。谢谢!

请注意,我需要单独跟踪每个用户。我将用我想要的数据填充临时表,但我只需要知道为一组用户循环此代码的方法。

最佳答案

如果您使用的是 SQL Server,则可以使用表变量来循环记录。

我在这里对其进行了简化,以向您展示概念 - 它应该足以让您入门。

-- Table variable to store the list of user ID
declare @UserIds table (UserId INT) 
declare @CurrentUserID INT

-- Load the table with the list of users we want to work with
INSERT INTO @UserIds (UserId)
SELECT userid
FROM AgentActivityLog   

-- loop through each user
WHILE EXISTS (SELECT UserId FROM @UserIds)
BEGIN

    -- select a user from the list of users
    SELECT TOP 1 @CurrentUserID = UserId 
    FROM @UserIds
    ORDER BY UserId ASC

    -- Do stuff with @CurrentUserID

   --Remove the current user id from the table variable - we are done with it
   DELETE FROM @UserIds WHERE UserId = @CurrentUserID
END

关于SQL 查询 – 执行循环但使用变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25798702/

相关文章:

SQL命令顺序

sql - MySQL查询从不同列复制日期

mysql - 从字段记录中选择计数日期的 SQL 查询

python - pandas:为列中的每一行计算 numpy 数组的平均值

PHP - 将 int 键转换为字符串?

python - 我可以设置一个 python while 循环运行直到没有任何变化吗?

mysql - OR 其他条件之间的冲突

c++ - valarray 是否有连续的内存对齐?

python - for循环中嵌套if语句中的特定缩进错误

c - C 中的循环语句