1

我正在尝试选择一些流量数据并为不同的流量方向创建总和,存储在 60 秒的存储桶中。简化表如下(时间戳为 unix epoch):

Timestamp      Source     Destination    Count
1              inside     outside          5
2              inside     outside          6
3              outside    inside           7
65             inside     inside           4
66             inside     outside          6
72             inside     outside          7

当前查询(进行分桶,但没有任何关于方向的信息)

SELECT sum(count) AS total FROM table GROUP BY round(timestamp/60)

这给了我每 60 秒“桶”的总计数,例如

Count
 18
 10
 7

现在,我迷路了(我可以在客户端代码中执行此操作,但如果可能的话,我有点想使用 SQL 执行此操作)。我想为每一行以内部作为源和目标作为外部的总和称为出站总和,对于每行外部在源和内部作为目标的称为出站的总和,以及一个称为内部的行,其中源和目标都在内部. 仍按 60 秒存储桶分组。即我想要回来的是:

Inbound  Outbound  Internal
   7        11        0
   0         6        4
   0         7        0

我的 SQL foo 很弱,我真的不知道从哪里开始(我怀疑我需要一个子选择,但我不确定如何构造它)。

4

2 回答 2

2
SELECT
  round(timestamp/60)             AS bucket,
  SUM(
    CASE WHEN source = 'inside'  AND destination = 'outside'
         THEN count ELSE 0
    END
  )                               AS outbound,
  SUM(
    CASE WHEN source = 'outside' AND destination = 'inside'
         THEN count ELSE 0
    END
  )                               AS inbound,
  SUM(
    CASE WHEN source = 'inside'  AND destination = 'inside'
         THEN count ELSE 0
    END
  )                               AS internal
FROM
  yourTable
GROUP BY
  round(timestamp/60)
于 2012-09-19T01:53:59.230 回答
1

你实际上应该能够做一个支点:

SELECT SUM(count) AS total
    , SUM(CASE 
              WHEN Source = 'outside' 
                   AND Destination = 'inside' 
                   THEN count  -- Use 1 if you only want to count each row
              ELSE 0 END) AS [Inbound]
    , SUM(CASE
              WHEN Source = 'inside' 
                  AND Destination = 'outside' 
                  THEN count
              ELSE 0 END) AS [Outbound]
    , SUM(CASE 
              WHEN Source = 'inside'
                  AND Destination = 'inside' 
                  THEN count
              ELSE 0 END) AS [Internal]
FROM table 
GROUP BY round(timestamp/60)
于 2012-09-19T01:53:29.420 回答