关于动态循环的问题
select '0-12' as 期间,count(distinct vin_no) as vin_no,
from VEHICLES A join wrk_mas b
on a.body_no=b.body_no
JOIN wrk_rev c
on b.work_no=c.bh_no
where datediff(m,a.sale_date,b.out_date) between 0 and 12
union all
select '13-24' as 期间,count(distinct vin_no) as vin_no,
from VEHICLES A join wrk_mas b
on a.body_no=b.body_no
JOIN wrk_rev c
on b.work_no=c.bh_no
where datediff(m,a.sale_date,b.out_date) between 13 and 24
union all
select '25-36' as 期间,count(distinct vin_no) as vin_no,
........................
以上是我写的SQL,主要实现,用户输入几年,然后,按月份期间显示出来。比如输入3年会显示出
0-12 1
13-24 2
25-36 3
如此类推
我想请假下有什么简便的方法吗,来实现这个?谢谢
------解决方案--------------------
SQL code
select CONVERT(varchar(5),d.be*12+1)+'-'+CONVERT(varchar(5),d.en*12),COUNT(distinct d.vin_no) as vin_no from (
select datediff(m,a.sale_date,b.out_date)/12 as be,(datediff(m,a.sale_date,b.out_date)/12)+1 as en, vin_no
from VEHICLES A join wrk_mas b
on a.body_no=b.body_no
JOIN wrk_rev c
on b.work_no=c.bh_no
) as d
group by d.be,d.en