You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多字段GROUP BY致计数膨胀?SQL按时间与事件类型统计异常

统计需求

统计时间范围在今日至一周前的记录总数,并按timestamp和event_type字段分组统计。

示例数据

id    timestamp    event_type

1     2024-01-31   signup
2     2024-02-10   login
3     2024-02-11   login
4     2024-02-12   logout
5     2024-02-14   signup
6     2024-02-14   signup
7     2024-02-15   login

期望查询结果

截至2024-02-15,近一周内的统计结果如下(2024-01-31的signup事件不应被统计):

count    timestamp    event_type
3        2024-02-15   login
1        2024-02-15   logout
2        2024-02-15   signup

问题与错误查询语句

最初仅按timestamp分组的查询结果远高于手动统计值,使用带窗口函数的查询得到了正确结果,但调整为同时按event_type分组后,各分组计数比实际值偏高约50%,调整后的错误查询语句如下:

with cumulative_counts as
    select top 10 timestamp, sum(records) over (order by timestamp rows between 7 preceding and 0 preceding) as count, event_type
    from (select timestamp, count(id), event_type as records
        from event_table
        where row_num = 1
        group by timestamp, event_type
        order by timestamp asc
    )
)
select * from cumulative_counts where timestamp = getdate()

内容的提问来源于stack exchange,提问作者Kevin2566

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:15:55