插入查询的麻烦

时间:2012-11-11 15:26:13

标签: sql

我有表TClientsPayment和字段

idcontract,idclient,last_paid_time,paid,left_to_pay

我需要将此表中的数据插入另一个带有字段的表TClientsPaymentsHistory

idcontract,idclient,last_paid_time,paid,late

其中latebit字段。 late可以是0或1.这取决于客户是否支付到25.xx.xxxx。如果不是late = 1。

如果我进行查询

insert into TClientPaymentHistory
select idcontract,
       idclient,
       last_paid_time,
       paid
from TClientsPayments

然后如何在此插入查询中设置late字段?

2 个答案:

答案 0 :(得分:2)

使用CASE子句中的SELECT表达式,这是一个如何执行此操作的伪代码:

insert into TClientPaymentHistory
select idcontract,
       idclient,
       last_paid_time,
       paid,
       CASE 
         WHEN DATEDIFF(day, last_paid_time, 'tell date here') <= something THEN 0
         ELSE 1
       END AS late     
from TClientsPayments

由于您没有指定正在使用的RDBMS,因此您需要确定获取日期差异的正确方法,具体取决于您使用的SQL方言。

答案 1 :(得分:2)

这样的事情,虽然你需要更清楚地了解情况:

Insert into TClientPaymentHistory (
  idcontract, idclient, last_paid_time, paid, late
)
Select
   idcontract,
   idclient,
   last_paid_time,
   paid,
   Case When last_paid_time < 25.xx.xxxx then 0 else 1 end
From
  TclientPayments