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

如何对比同表同列不同行的值,查询同账号下StartDate不同的记录

实现方案

方案1:使用窗口函数(兼容MySQL8.0+、PostgreSQL、SQL Server等支持窗口函数的主流数据库)

通过分区统计每个AccountNumber下不同StartDate的数量,过滤出数量大于1的所有记录即可:

WITH meter_stat AS (
    SELECT 
        ROW_NUMBER() OVER (ORDER BY AccountNumber DESC, StartDate) AS RowNo,
        AccountNumber,
        MeterNumber,
        StartDate,
        -- 按账号分组统计不同的启动日期数量
        COUNT(DISTINCT StartDate) OVER(PARTITION BY AccountNumber) AS diff_date_count
    FROM Meter
)
SELECT RowNo, AccountNumber, MeterNumber, StartDate 
FROM meter_stat 
WHERE diff_date_count > 1;

方案2:使用子查询关联(全数据库兼容,支持MySQL5.x等低版本数据库)

先通过分组查询拿到存在多个不同StartDate的AccountNumber列表,再关联原表取出对应所有记录:

SELECT 
    ROW_NUMBER() OVER (ORDER BY m.AccountNumber DESC, m.StartDate) AS RowNo,
    m.AccountNumber,
    m.MeterNumber,
    m.StartDate
FROM Meter m
INNER JOIN (
    -- 筛选出存在多个不同启动日期的账号
    SELECT AccountNumber
    FROM Meter
    GROUP BY AccountNumber
    HAVING COUNT(DISTINCT StartDate) > 1
) t ON m.AccountNumber = t.AccountNumber;

注意:你提供的测试表创建语句中AccountNumber字段存在拼写错误(误写为AccountNumer,少了字母b),执行测试脚本前可先修正字段名。如果不需要返回结果的RowNo序号,直接删除查询语句中对应ROW_NUMBER部分即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 05:54:04