SQL查询–执行循环,但使用变量数组
下面是我正在编写的代码示例SQL查询–执行循环,但使用变量数组,sql,arrays,loops,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 StateD
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;
我想为一组用户ID执行此任务,而不是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
您使用的是什么rdbms?这是SQL Server、Oracle、MySQL吗?好的,请参阅下面的答案。工作非常完美!谢谢你,多纳尔!这个网站很棒!