先创建一个自定义函数:<br>create function f_sjd(@t1 datetime, @t2 datetime) <br>returns varchar(50)<br>as<br>begin<br> declare @n int<br> declare @result varchar(50)<br> set @n=DateDiff(DAY,@t1,@t2)<br> if @n>=0 and @n<=30 set @result='0-30天'<br> else if @n>30 and @n<=60 set @result='31-60天'<br> else if @n>60 and @n<=90 set @result='61-90天'<br> else if @n>90 and @n<=120 set @result='91-120天'<br> else if @n>120 and @n<=150 set @result='121-150天'<br> else if @n>150 and @n<=180 set @result='151-180天'<br> else set @result='180天以上' <br> return @result<br>end<br>然后:<br>--示例数据:<br>declare @tb table([ID] varchar(3), [GROUP] varchar(10), [QUANTITY]int, [INDATE] Datetime)<br>insert into @tb<br>select '001','A',1000,'2008-1-2' union all<br>select '002','B',3000,'2008-1-16' union all<br>select '001','A',2000,'2008-2-10' union all<br>select '003','A',1500,'2008-2-20' union all<br>select '004','B',3000,'2008-2-22' union all<br>select '005','C',2800,'2008-3-12'<br><br>select<br> [GROUP],[ID],<br> sum(case [时间段] when '0-30天' then [QUANTITY] else 0 end) as [0-30天],<br> sum(case [时间段] when '31-60天' then [QUANTITY] else 0 end) as [31-60天],<br> sum(case [时间段] when '61-90天' then [QUANTITY] else 0 end) as [61-90天],<br> sum(case [时间段] when '91-120天' then [QUANTITY] else 0 end) as [91-120天],<br> sum(case [时间段] when '121-150天' then [QUANTITY] else 0 end) as [121-150天],<br> sum(case [时间段] when '151-180天' then [QUANTITY] else 0 end) as [151-180天],<br> sum(case [时间段] when '180天以上' then [QUANTITY] else 0 end) as [180天以上]<br>from<br>(<br>select dbo.f_sjd([INDATE], getDate()) as [时间段],[ID],[GROUP],sum(QUANTITY) [QUANTITY]<br>from @tb<br>group by dbo.f_sjd([INDATE], getDate()),[GROUP],[ID]<br>) t<br>group by [GROUP],[ID]<br>/*<br>GROUP ID 0-03天 31-60天 61-90天 91-120天 121-150天 151-180天 180天以上<br>A 001 0 0 0 0 0 2000 1000<br>B 002 0 0 0 0 0 3000 0<br>A 003 0 0 0 0 1500 0 0<br>B 004 0 0 0 0 3000 0 0<br>C 005 0 0 0 0 2800 0 0<br>*/