根据时间戳计算更改

时间:2015-05-26 09:31:32

标签: sql

我有一张桌子

timestamp   ip        score
1432632348  1.2.3.4   9
1432632434  5.6.7.8   8
1432632447  1.2.3.4   9
1432632456  1.2.3.4   8
1432632460  5.6.7.8   8
1432632464  1.2.3.4   9

时间戳是连续的,但没有任何频率。我想根据IP计算分数变化的次数。所以在示例中结果将是:

ip      count
1.2.3.4 3
5.6.7.8 1

我该怎么做? (注意:计数明显不起作用:1.2.3.4改变了3次,但有2个不同的分数)

3 个答案:

答案 0 :(得分:2)

select ip,
       sum(case when score <> (select t2.score from table t2
                               where t2.timestamp = (select max(timestamp) from table
                                                     where ip = t2.ip
                                                       and timestamp < t1.timestamp)
                                 and t1.ip = t2.ip) then 1 else 0 end)
from table t1
group by ip

答案 1 :(得分:1)

虽然这个要求并不常见,但也并不罕见。基本上,您需要确定数据列何时发生更改。

数据是关系数据,因此解决方案是关系。不需要游标或CTE或ROW_NUMBER()s或临时表或GROUP BYs或脚本或触发器。 DISTINCT无效。解决方案很简单。但你必须保持你的关系帽。

    SELECT  COUNT( timestamp )
        FROM (

        SELECT  timestamp,
                ip,
                score,
                [score_next] = (
            SELECT  TOP 1
                    score               -- NULL if not exists
                FROM MyTable
                WHERE ip        = MT.ip
                AND   timestamp > MT.timestamp
                )

            FROM MyTable MT

            ) AS X

        WHERE score      != score_next  -- exclude unchanging rows
        AND   score_next != NULL

我注意到对于您提供的数据,输出应为:

    ip      count
    1.2.3.4     2
    5.6.7.8     0
  • 如果你被计算到每个ip的最后得分,但尚未改变,那么你的数字将会超过1&#34;。要获取您的计数,请删除最后一行代码。

  • 如果您已将明确的0计算为起始值,请将1添加到COUNT().

如果您有兴趣进一步讨论这个不常见的问题,我已在this Answer中给予了全面的处理。

答案 2 :(得分:-2)

select ip ,
       count(distinct score) 
 from YourTable 
 group by ip

enter image description here