--举个简单的示例--创建一个时间范围表,用来保存用户定义的查询区间时间段名 开始时间 结束时间 --字符型
--------- ----------- ----------
小于1个月 -1 30 --以天为单位,负数表示不限制
1~2个月 31 60 --1~2个月的
2~3个月 61 90 --2~3个月的
3~6个月 91 180 --3~6个月的
半年以上 181 -1 --大于半年的--查询的处理(横向显示的)
declare @s varchar(8000)
set @s=''
select @s=@s+',['+时间段名+']=sum(case when '
+case
when 开始时间=-1
then 'datediff(day,时间字段,getdate())<'+结束时间
when 结束时间=-1
then 'datediff(day,时间字段,getdate())>'+开始时间
else 'datediff(day,时间字段,getdate()) between '
+开始时间+' and '+结束时间
end+' then 金额 else 0 end)'
from 时间范围表
exec('select 单位名称'+@s+'
from 表
group by 单位名称')
--------- ----------- ----------
小于1个月 -1 30 --以天为单位,负数表示不限制
1~2个月 31 60 --1~2个月的
2~3个月 61 90 --2~3个月的
3~6个月 91 180 --3~6个月的
半年以上 181 -1 --大于半年的--查询的处理(横向显示的)
declare @s varchar(8000)
set @s=''
select @s=@s+',['+时间段名+']=sum(case when '
+case
when 开始时间=-1
then 'datediff(day,时间字段,getdate())<'+结束时间
when 结束时间=-1
then 'datediff(day,时间字段,getdate())>'+开始时间
else 'datediff(day,时间字段,getdate()) between '
+开始时间+' and '+结束时间
end+' then 金额 else 0 end)'
from 时间范围表
exec('select 单位名称'+@s+'
from 表
group by 单位名称')
product_id(产品代码) inoutdate(出入库日期) qty(数量)
001 2004-01-01 10
001 2004-01-03 -8
001 2004-01-04 -1
001 2004-01-05 5
001 2004-01-07 -6
其中数量为正表示入库,数量为负表示出库,现要计算任意日期时库存产品的库存天数。系统默认先进先出。
比如查询2004-01-02日库龄,则为10个、库龄为1天
查询2004-01-03日库龄,则为2个、库龄为2天
查询2004-01-04日库龄,则为1个、库龄为3天
查询2004-01-05日库龄,则为1个、库龄为4天和5个、库龄为0天
查询2004-01-06日库龄,则为1个、库龄为5天和5个、库龄为1天
查询2004-01-07日库龄,则为0个、库龄为0
语句:
declare @dt datetime,@pid char(3)
set @dt='2004-01-06'
set @pid='001'declare @p table ( pid char(3),iodt datetime, qty int)insert @p select '001', '2004-01-01', 10
union select '001', '2004-01-03', -8
union select '001', '2004-01-04', -1
union select '001', '2004-01-05', 5
union select '001', '2004-01-07', -6
union select '002', '2004-01-06', 20
select pid,库龄,case when qty>数量 then 数量 else qty end as 数量
from ( select pid,
datediff(day,iodt,@dt) as 库龄,
qty,
( select isnull(sum(qty),0)
from @p
where pid=@pid and iodt<=@dt and (iodt<=a.iodt or (iodt>a.iodt and qty<0))
)
as 数量
from @p a
where pid=@pid and iodt<=@dt and qty>0
) b
where 数量>0