写一条“系统自动检查超过6个月没有下单的客户,并自动添加一条客户流失预警记录。”的sql语句,涉及到了订单表,客户表 订单表 Orders  列 :OrderID(订单编号)、CusID(客户编号)、OrderDate(顶购时间)客户表:CusID(客户编号), CusName(客户名称), CusDate(成为客户的时间)
例如:订单时间为:2011年4月29日 时 也就是今天 2011/10/29日 就要添加在客户流失表中一条流失预警了
难点是:怎样判断6个月没有下单的客户????????????????、

解决方案 »

  1.   

    select * from Customer as a where not exists(select 1 from Orders where CusID=a.CusID and datediff(m,OrderDate,getdate())>6)
      

  2.   

    select * from Customer as a 
    where not exists(select 1 from Orders 
    where CusID=a.CusID and dateadd(m,datediff(m,OrderDate,getdate()),OrderDate)<getdate())--按天数计算时
      

  3.   

    select * from customer t where not exists(select 1 from orders where cusID=t.cusID and datediff(mm,OrderDate,getdate())>6)
      

  4.   

    自认为不NB的试试:--创建一个作业,每天执行或者每月执行
    insert into 客户流失预警(客户编号,客户名称,最后时间)
    select a.cusid,a.cusname,b.orderdate
    from 客户表 a inner join 订单表 b on a.cusid=b.cusid
    where datediff(m,b.orderdate,getdate())>6 and not exists(
    select 1 from 订单表 where curid=b.cusid and orderdate>a.orderdate)
      

  5.   

    --创建一个作业,每天执行或者每月执行
    insert into 客户流失预警(客户编号,客户名称,最后时间)
    select a.cusid,a.cusname,b.orderdate
    from 客户表 a inner join 订单表 b on a.cusid=b.cusid
    where datediff(m,b.orderdate,getdate())>6 and not exists(
    select 1 from 订单表 where curid=b.cusid and orderdate>a.orderdate)
    and not exists(select 1 from 客户流失预警 where 客户编号=a.a.cusid and 客户名称=a.cusname and 最后时间=b.b.orderdate)
      

  6.   

    insert 客户流失表
    select * from Customer as a 
    where not exists(select 1 from Orders 
    where CusID=a.CusID and dateadd(m,datediff(m,OrderDate,getdate()),OrderDate)<getdate())--按天数计算时可以用作业的方式新增到流失表企业管理器 
    --管理 
    --SQL Server代理 
    --右键作业 
    --新建作业 
    --"常规"项中输入作业名称 
    --"步骤"项 
    --新建 
    --"步骤名"中输入步骤名 
    --"类型"中选择"Transact-SQL 脚本(TSQL)" --如:下面的SQL腳本
    --"数据库"选择执行命令的数据库 
    --"命令"中输入要执行的语句: 
                          EXEC 存储过程名 ... --该存储过程用于创建表 --确定 
    --"调度"项 
    --新建调度 
    --"名称"中输入调度名称 
    --"调度类型"中选择你的作业执行安排 
    --如果选择"反复出现" 
    --点"更改"来设置你的时间安排  
    然后将SQL Agent服务启动,并设置为自动启动,否则你的作业不会被执行 设置方法: 
    我的电脑--控制面板--管理工具--服务--右键 SQLSERVERAGENT--属性--启动类型--选择"自动启动"--确定.