如何统计两个主键不同表的每分钟记录总数及均值
统计两张时间序列表的每分钟记录总数
表结构与数据
第一张表数据
| opt | opt_date |
|---|---|
| 1 | 2023-04-10 12:20:00 |
| 2 | 2023-04-10 12:20:03 |
| 3 | 2023-04-10 12:21:03 |
| 4 | 2023-04-10 12:22:03 |
| 5 | 2023-04-10 13:05:00 |
| 6 | 2023-04-10 13:05:10 |
第二张表数据
| opt | opt_date |
|---|---|
| 7 | 2023-04-10 12:21:00 |
| 9 | 2023-04-10 13:05:00 |
单表统计每分钟记录数的查询
原用于单表统计的SQL语句:
select datepart(hh,opt_date), datepart(mi,opt_date), count(*) from mytable group by datepart(hh,opt_date), datepart(mi,opt_date) order by datepart(hh,opt_date), datepart(mi,opt_date)
需求与预期结果
需统计两张表每分钟的记录总数,预期结果如下(部分分钟仅单表有记录):
| opt_date | count(*) |
|---|---|
| 2023-04-10 12:20:00 | 2 |
| 2023-04-10 12:21:03 | 2 |
| 2023-04-10 12:22:03 | 1 |
| 2023-04-10 13:05:00 | 4 |
解决方案SQL
方案1:统一显示分钟起始时间
通过UNION ALL合并两表数据,再按分钟级别截断时间分组统计:
select -- 将时间截断至分钟起始点,确保同一分钟的记录归为一组 dateadd(minute, datediff(minute, 0, opt_date), 0) as opt_date_minute, count(*) as total_count from ( -- 合并两张表的时间字段,保留所有记录 select opt_date from table1 union all select opt_date from table2 ) combined_data group by dateadd(minute, datediff(minute, 0, opt_date), 0) order by opt_date_minute;
方案2:匹配预期结果的时间显示格式
若需要显示该分钟内的某条具体时间(如预期结果中的非起始时间),可调整为取分钟内最早的时间作为展示值:
select min(opt_date) as opt_date, count(*) as total_count from ( select opt_date from table1 union all select opt_date from table2 ) combined_data group by datepart(hh, opt_date), datepart(mi, opt_date) order by opt_date;
关键说明
UNION ALL比UNION更高效,因为不需要对合并后的数据去重,适合统计总记录数的场景;- 两种方案均通过小时+分钟或分钟截断的方式实现按分钟分组,确保跨表的同分钟记录被正确聚合。
内容的提问来源于stack exchange,提问作者nana kh
相关产品推荐
相关产品推荐

