0

我在下面有这段代码(在 sql server 2017 上运行):

WITH selection AS (
    SELECT servertimestamp 
    FROM eventlog 
    WHERE servertimestamp BETWEEN '5/29/2018' AND DATEADD(dd, +1, '6/29/2019')

    AND (attributes LIKE '%N<=>PeopleIn%'))
(SELECT DATEADD(HOUR, DATEDIFF(HOUR, 0, servertimestamp) - (DATEDIFF(HOUR, 0, servertimestamp) % 2), 0) as timestamp , COUNT(servertimestamp) AS GONE_OUT
FROM selection
WHERE DATEPART(hh, servertimestamp) BETWEEN 8 AND 20

GROUP BY DATEADD(HOUR, DATEDIFF(HOUR, 0, servertimestamp) - (DATEDIFF(HOUR, 0, servertimestamp) % 2), 0))
ORDER BY timestamp

下面的屏幕截图还显示了执行代码的结果:

在此处输入图像描述

这段代码的作用是显示每天有多少人进入建筑物。数据以 2 小时为单位进行分组。

我想要做的是添加一个列,显示在我已经使用的相同时间段内有多少人离开了大楼。下面我给你一个我想做的例子:

在此处输入图像描述

请注意,在第 6 行,我使用了 LIKE 运算符(属性 LIKE '%N<=>PeopleIn%')。这意味着对于附加列,我必须做出类似的选择,但使用 属性 LIKE '%N<=>PeopleOut%'有所不同。

我可以使用 UNION 运算符来实现吗?还有其他更明显或更简单的方法吗?

您的帮助将不胜感激,谢谢。

4

2 回答 2

0

UNION 按执行顺序附加结果集。UNION 不会是我解决这个问题的首选。

我在您的屏幕截图中看到的是 GONE_OUT 和 CAME_IN 分组在一个唯一的日期时间和一个聚合值分组的类别上。您可能有两个(子)查询,一个用于 GONE_OUT,一个用于 CAME_IN,然后建立关系。

SELECT *
FROM GONE_OUT AS go 
LEFT JOIN CAME_IN AS ci ON go.timestamp = ci.timestamp
于 2018-07-05T09:14:07.610 回答
0

您可以通过根据活动标记 CTE 中的 servertimestamp 字段,然后总结标签来做到这一点。

WITH selection
AS (
  SELECT 
    servertimestamp
    ,CASE WHEN attributes LIKE '%N<=>PeopleIn%' THEN 1 ELSE 0 END AS PPL_IN
    ,CASE WHEN attributes LIKE '%N<=>PeopleOut%' THEN 1 ELSE 0 END AS PPL_OUT
  FROM eventlog
  WHERE 
    servertimestamp BETWEEN '5/29/2018' AND DATEADD(dd, + 1, '6/29/2019')
    AND 
    (attributes LIKE '%N<=>PeopleIn%'
     OR
     attributes LIKE '%N<=>PeopleOut%')
  ) 
  (
    SELECT 
      DATEADD(HOUR, DATEDIFF(HOUR, 0, servertimestamp) - (DATEDIFF(HOUR, 0, servertimestamp) % 2), 0) AS TIMESTAMP
      ,SUM(PPL_OUT) AS GONE_OUT
      ,SUM(PPL_IN) AS CAME_IN
    FROM selection
    WHERE DATEPART(hh, servertimestamp) BETWEEN 8
        AND 20
    GROUP BY DATEADD(HOUR, DATEDIFF(HOUR, 0, servertimestamp) - (DATEDIFF(HOUR, 0, servertimestamp) % 2), 0)
   )
ORDER BY TIMESTAMP
于 2018-07-05T11:18:46.877 回答