当前位置: 代码迷 >> Sql Server >> 求数据库脚本大神帮忙!解决方法
  详细解决方案

求数据库脚本大神帮忙!解决方法

热度:21   发布时间:2016-04-24 18:42:31.0
求数据库脚本大神帮忙!
tb_records:
name           num           date
张三           0002          2013-12-12 12345
李四           0002          2013-12-15 12345
王五           0002          2013-12-20 12345
赵六           0002          2013-12-30 12345
王二           0005          2014-01-13 12345
麻子           0005          2014-02-13 12345

求相同num,其他时间在当前行时间过去3天内的记录数和过去7天内的记录数,最后输出结果如下。

name           num           date                     count3     count7
张三           0002          2013-12-12 12345          1          1
李四           0002          2013-12-15 12345          2          2
王五           0002          2013-12-20 12345          1          2
赵六           0002          2013-12-30 12345          1          1
王二           0005          2013-12-13 12345          2          2
麻子           0005          2013-12-13 12345          2          2

小弟尝试各种方案均不通过,无奈之下集思广益,先谢谢各位!
------解决方案--------------------

create table tb_records(name varchar(20),  num varchar(10),  date datetime)

insert into tb_records
select '张三',           '0002',          '2013-12-12' union all
select '李四',           '0002',          '2013-12-15' union all
select '王五',           '0002',          '2013-12-20' union all
select '赵六',           '0002',          '2013-12-30' union all
select '王二',           '0005',          '2013-12-13' union all
select '麻子',           '0005',          '2013-12-13' 
go

select *,
       (select count(*) from tb_records t2 
        where t1.num = t2.num and t2.date <= t1.date and datediff(day,t2.date,t1.date)<=3) as count3,
       
       (select count(*) from tb_records t2 
        where t1.num = t2.num and t2.date <= t1.date and datediff(day,t2.date,t1.date)<=7) as count7
                

from tb_records t1
/*
name num date count3 count7
张三 0002 2013-12-12 00:00:00.000 1 1
李四 0002 2013-12-15 00:00:00.000 2 2
王五 0002 2013-12-20 00:00:00.000 1 2
赵六 0002 2013-12-30 00:00:00.000 1 1
王二 0005 2013-12-13 00:00:00.000 2 2
麻子 0005 2013-12-13 00:00:00.000 2 2
*/

------解决方案--------------------
引用:
tb_records:
name           num           date
张三           0002          2013-12-12 12345
  相关解决方案