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

在MS SQL Server中如何依据上月记录判定客户为老客/新客?

实现客户新老客判定的SQL方案

前提假设

假设你的业务表(示例命名为CustomerTransactions)包含核心字段:

  • CustomerID:客户唯一标识ID
  • TransactionDate:客户产生业务记录的日期

方法1:窗口函数+存在性判断(高效推荐)

先按客户+月份去重,避免同一客户同月多条记录干扰判定,再通过存在性检查判断上月是否有记录:

WITH CustomerMonthlyRecords AS (
    SELECT 
        CustomerID,
        DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) AS RecordMonth
    FROM CustomerTransactions
    GROUP BY CustomerID, YEAR(TransactionDate), MONTH(TransactionDate)
)
SELECT 
    CustomerID,
    RecordMonth,
    CASE 
        WHEN EXISTS (
            SELECT 1 
            FROM CustomerMonthlyRecords cmr2
            WHERE cmr2.CustomerID = cmr1.CustomerID
              AND cmr2.RecordMonth = DATEADD(MONTH, -1, cmr1.RecordMonth)
        ) THEN 'existing(老客)'
        ELSE 'new(新客)'
    END AS CustomerType
FROM CustomerMonthlyRecords cmr1
ORDER BY CustomerID, RecordMonth;

方法2:自关联查询

通过表自关联匹配客户上月记录,根据关联结果判定新老客:

WITH CustomerMonthlyRecords AS (
    SELECT 
        CustomerID,
        DATEFROMPARTS(YEAR(TransactionDate), MONTH(TransactionDate), 1) AS RecordMonth
    FROM CustomerTransactions
    GROUP BY CustomerID, YEAR(TransactionDate), MONTH(TransactionDate)
)
SELECT 
    cmr1.CustomerID,
    cmr1.RecordMonth,
    CASE 
        WHEN cmr2.CustomerID IS NOT NULL THEN 'existing(老客)'
        ELSE 'new(新客)'
    END AS CustomerType
FROM CustomerMonthlyRecords cmr1
LEFT JOIN CustomerMonthlyRecords cmr2
    ON cmr1.CustomerID = cmr2.CustomerID
    AND cmr2.RecordMonth = DATEADD(MONTH, -1, cmr1.RecordMonth)
ORDER BY cmr1.CustomerID, cmr1.RecordMonth;

结果验证

对应你给出的示例场景:

  • Customer A 2022年12月:上月(2022年11月)有记录 → 判定为existing(老客)
  • Customer A 2023年1月:上月(2022年12月)有记录 → 判定为existing(老客)
  • Customer B 2022年11月:上月(2022年10月)无记录 → 判定为new(新客)
  • Customer B 2023年1月:上月(2022年12月)无记录 → 判定为new(新客)

若你的业务表结构有差异,仅需调整表名、字段名即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:12:47