将查询结果存储到SQL Server中的A变量

时间:2018-10-22 04:50:57

标签: sql-server database ssms

我有以下数据:

CREATE TABLE TimeLog 
(
     [User] NVARCHAR(6),
     [Event] NVARCHAR(3),
     [Time] DATETIME
);

INSERT INTO TimeLog 
VALUES (N'Mark', N'IN', '2015-04-15 00:31:00'),
       (N'Mark', N'IN', '2015-04-16 20:10:00'),
       (N'Mark', N'IN', '2015-04-21 14:59:00'),
       (N'Mark', N'OUT', '2015-04-22 01:01:00'),
       (N'Mark', N'IN', '2015-04-22 10:46:00'),
       (N'Mark', N'OUT', '2015-04-23 00:58:00'),
       (N'Mark', N'IN', '2015-04-23 14:50:00'),
       (N'Mark', N'OUT', '2015-04-24 01:37:00'),
       (N'Mark', N'OUT', '2015-04-25 01:01:00'),
       (N'Mark', N'OUT', '2015-04-27 00:57:00'),
       (N'Mark', N'IN', '2015-04-17 10:32:00'),

我通过查询将IN和OUT分为不同的列:

SELECT 
    [UserName], [IN], [OUT] 
FROM
    (SELECT 
         ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) + ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) % 2 AS [PairID],
         *
     FROM  
         [dbo].[AttendanceEvents] 
     WHERE
         UserName = 'Mark') DS
PIVOT
    (MAX([EventTime]) 
        FOR [EventName] IN ([IN], [OUT])
    ) PVT
ORDER BY 
    [PairID];

现在,我想将此查询的结果存储到变量或表中,以便从每个Datetime列(IN和OUT这两列)中找出平均时间。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以只定义CTE,然后查询:

WITH cte AS (
    SELECT [UserName], [IN], [OUT] 
    FROM
    (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) +
          ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) % 2 AS [PairID]
        FROM [dbo].[AttendanceEvents]
        WHERE UserName = 'Mark'
        ) DS
        PIVOT
        (
            MAX([EventTime]) FOR [EventName] IN ([IN], [OUT])
        ) PVT
    ) t
)

SELECT AVG([IN]) AS avg_in, AVG([OUT]) AS avg_out
FROM cte;

答案 1 :(得分:1)

最简单的解决方案是即时执行:

SELECT [UserName]
  ,AVG(DATEDIFF(minute,[OUT],[IN])) AvgMinutes 

FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) + ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) % 2 AS [PairID]
      ,*
FROM [dbo].[AttendanceEvents] Where UserName = 'Mark'
) DS
PIVOT
(
MAX([EventTime]) FOR [EventName] IN ([IN], [OUT])
) PVT
GROUP BY [UserName];

但是,如果您想将其插入某些内容,请使用insert

某些内容可能是本地临时表,全局临时表或表变量。

或者您可以使用前面提到的CTE方法。

这是一个样本。您必须使用适当的数据类型。我刚刚使用了VARCHAR

我删除了order by,因为从未以任何顺序插入数据-只有当您再次选择时才将其插入。

DECLARE @MyTableVariable TABLE (
    Username VARCHAR(50),
    In DATETIME,
    Out DATETIME
)

INSERT INTO @MyTableVariable (UserName, In, Out)
SELECT [UserName]
  ,[IN]
  ,[OUT] 
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) + ROW_NUMBER() OVER (PARTITION BY [UserName] ORDER BY [EventTime]) % 2 AS [PairID]
      ,*
FROM [dbo].[AttendanceEvents] Where UserName = 'Mark'
) DS
PIVOT
(
MAX([EventTime]) FOR [EventName] IN ([IN], [OUT])
) PVT;