0

我有一个表,TB其中包含Time, User_id, State数据如下所示的列。

INSERT INTO TB
  (Time, User_id, State)
VALUES
  (1, 1, 'VA'),
  (1, 2, 'VA'),
  (1, 2, 'DC'),
  (2, 1, 'VA'),
  (2, 2, 'MD'),
  (3, 1, 'MD'),
  (3, 112, 'MD'),
  (3, 134, 'VA'),
  (3, 111, 'MD'),
  (4, 12, 'VA'),
  (4, 22, 'MD')
;

我想要每 2 秒User_id给定的唯一计数。State = 'DC'结果应如下所示:

NewTime | Count  
   1    |  1
   2    |  0

当计数为 0 时,我得到了打印出 0 的答案

SELECT  TIME,
        SUM(CASE WHEN State = 'DC' THEN 1 ELSE 0 END) Count
FROM    TB
GROUP   BY Time

并使用获取时间范围内的唯一计数

SELECT
    ((Time - 1) / 2) + 1 as NewTime,
    COUNT(DISTINCT User_id) as Count
FROM ... 
GROUP BY ((Time - 1) / 2) + 1

但我不确定如何将这两者结合起来以获得我想要的结果。

提前致谢。

4

1 回答 1

1

您是否正在寻找这个:

SELECT
    ((Time - 1) / 2) + 1 as NewTime,
    COUNT(DISTINCT case when state = 'DC' then User_id end) as Count
FROM ... 
GROUP BY ((Time - 1) / 2) + 1

这假设您每两秒就有一些记录(尽管不一定是 DC)。

于 2013-02-27T19:02:34.800 回答