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

如何过滤MySQL中同一时间戳的智能电表重复数据?

智能电表重复时间戳记录过滤方案

针对智能电表历史数据中同一smartMeterId+time组合的重复记录,需要过滤重复仅保留每组一条的需求,以下是几种正确实现方式:

问题分析

你原SQL的核心问题在于ROW_NUMBER()的ORDER BY time:同一分组内所有行的time完全相同,导致排序逻辑不稳定,每次执行可能返回不同的row_num=1记录。同时若需处理所有电表数据,可去掉WHERE中的smartMeterId = 'sss'条件。

实现方案

方案1:优化窗口函数(通用兼容)

通过指定唯一列(如id)作为排序依据,确保每组重复记录稳定保留一条:

WITH RankedRows AS (
  SELECT
    id,
    smartMeterId,
    unitConsumed,
    time,
    ROW_NUMBER() OVER (PARTITION BY smartMeterId, time ORDER BY id) AS row_num
  FROM
    demodb.SmartMeterUsageHistory
)
SELECT
  id,
  smartMeterId,
  unitConsumed,
  time
FROM
  RankedRows
WHERE
  row_num = 1
-- 如需过滤特定电表,添加以下条件
-- AND smartMeterId = 'sss'
;

方案2:PostgreSQL专属简洁语法

使用DISTINCT ON直接按指定列去重,配合排序确保结果稳定:

SELECT DISTINCT ON (smartMeterId, time)
  id,
  smartMeterId,
  unitConsumed,
  time
FROM
  demodb.SmartMeterUsageHistory
ORDER BY smartMeterId, time, id
-- 如需过滤特定电表,添加以下条件
-- WHERE smartMeterId = 'sss'
;

方案3:GROUP BY兼容方案(适用于老版本数据库)

通过聚合函数选取每组的唯一记录(示例取最小id),需确保同一smartMeterId+time下的unitConsumed值一致:

SELECT
  MIN(id) AS id,
  smartMeterId,
  unitConsumed,
  time
FROM
  demodb.SmartMeterUsageHistory
-- 如需过滤特定电表,添加以下条件
-- WHERE smartMeterId = 'sss'
GROUP BY
  smartMeterId, time, unitConsumed
;

若同一smartMeterId+time下存在不同unitConsumed值,需先明确业务规则(如取平均值、最大值),再调整聚合逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:32:50