我有两个表,一个是列表表,这是表的数据类型
create table List(
CustNo Int,
NoOverDue money,
OverDue1 money,
OverDue2 money,
OverDue3 money,
OverDue4 money
)
和一个表调用 tablecost
create table tablecost(
custno int,
cost money,
DueDate datetime,
ListDate datetime
)
我的表有太多数据,所以我创建了几个数据列供您更快地解决我的问题。
insert into tablecost values (1,100,'20130812','20130712')
insert into tablecost values (2,100,'20130612','20130712')
insert into tablecost values (3,100,'20130512','20130712')
insert into tablecost values (4,100,'20130412','20130712')
insert into tablecost values (5,100,'20130312','20130712')
insert into tablecost values (6,100,'20130112','20130712')
List
目的是在我的表中插入:
如果我的到期日期没有结束,它将插入到 nooverdue 中。
如果在 1 到 30 天之间逾期,它将插入逾期 1。
如果在 31 到 60 天之间逾期,它将插入逾期 2。
如果在 61 到 90 天之间逾期,它将插入逾期 3。
如果在 91 到 120 天之间逾期,它将插入逾期 4。
这是我在查询上尝试的,它工作正常:
insert into List (CustNo, NoOverDue)
select CustNo,Cost from TableCost
where DueDate > GetDate()
and convert(varchar(8),ListDate,112) between '20130711' and '20130713'
insert into List (CustNo, OverDue1)
select CustNo,Cost from TableCost
where DueDate between DateAdd(Day,-30,GetDate()) and DateAdd(Day,-1,GetDate())
and convert(varchar(8),ListDate,112) between '20130711' and '20130713'
insert into List (CustNo, OverDue2)
select CustNo,Cost from TableCost
where DueDate between DateAdd(Day,-60,GetDate()) and DateAdd(Day,-31,GetDate())
and convert(varchar(8),ListDate,112) between '20130711' and '20130713'
insert into List (CustNo, OverDue3)
select CustNo,Cost from TableCost
where DueDate between DateAdd(Day,-90,GetDate()) and DateAdd(Day,-61,GetDate())
and convert(varchar(8),ListDate,112) between '20130711' and '20130713'
insert into List (CustNo, OverDue4)
select CustNo,Cost from TableCost
where DueDate between DateAdd(Day,-120,GetDate()) and DateAdd(Day,-91,GetDate())
and convert(varchar(8),ListDate,112) between '20130711' and '20130713'
我的问题是,是否有任何可能的方法来缩短或改进查询代码?让这个查询只插入到这个表中似乎很长