1

我有一张这样的桌子

Time   |  user_id
12100  |    23
12100  |    23
12100  |    22
12100  |    19
12100  |    20
...
12160  |    273
12160  |    223
12160  |    1223
...

时间以秒为单位。我正在寻找一种方法来在一分钟内获取唯一 user_id 的计数并让结果表看起来像这样

Minute  |  Count
  1     |  36
  2     |  100
...

假设它从 12100 开始,所以第 1 分钟来自12100 ~ 12159,第 2 分钟来自12160 to 12219

非常感谢您的帮助。

更新:(这是我尝试过的,但似乎包含重复项)

SELECT ROW_NUMBER() OVER (ORDER BY [Time]) AS [Row]
        , [Time]
        , COUNT(DISTINCT([user_id])) as [Count]
    INTO [table].[dbo].[temp]
  FROM [db].[dbo].[table]
  GROUP BY [Time]

  SELECT t.[Minute], SUM(t.[Count]) AS [Count]
    FROM
    (SELECT (ROW_NUMBER() OVER (ORDER BY [Row]) + 59)/60 AS [Minute]
            , SUM([Count]) AS [Count]
        FROM [db].[dbo].[temp]
        GROUP BY [Row]) AS t
    GROUP BY t.[Minute]
    ORDER BY t.[Minute]

DROP TABLE [db].[dbo].[temp]
4

1 回答 1

3

创建一个表达式,将时间转换为您的目标分钟数并按以下方式分组:

select
    ((Time - 12000) / 60) + 1 as Minute,
    count(distinct user_id) as Count
from ... 
group by ((Time - 12000) / 60) + 1
于 2013-02-17T00:51:11.327 回答