1

我选择了完美的选择。

update ClientS set StatusID=4
where ClientID= (select P.ClientID
   ,LastName+' '+FirstName as Name 
   ,Address
   ,max(p.PickupDate)as 'Last Pickup'
   ,DATEDIFF(month,max(p.PickupDate),GETDATE())as'last pickup was months ago'
from Pickup P
join Clients C on P.ClientID= C.ClientID
where WIC=0 and C.StatusID = 1 or WIC=0 and C.StatusID = 2
group by p.clientid, lastname + ' ' + firstname,address
order by 4)

我需要基于last pickup was months ago此选择中的一个更新语句。我需要更新表中的客户StatusIDClients并将其设置为 4,仅针对此选择中最后一次取货时间超过 2 个月的客户。到目前为止我有这个

create procedure pr_UpdateStatusHwoPickupMoreThanTwoM 
AS
update ClientS set StatusID=4
where ClientID= (select P.ClientID
   ,LastName+' '+FirstName as Name 
   ,Address
   ,max(p.PickupDate)as 'Last Pickup'
   ,DATEDIFF(month,max(p.PickupDate),GETDATE())as'last pickup was months ago'
from Pickup P
join Clients C on P.ClientID= C.ClientID
where WIC=0 and C.StatusID = 1 or WIC=0 and C.StatusID = 2
group by p.clientid, lastname + ' ' + firstname,address
order by 4)

我知道这是不对的,我需要以某种方式指定最后一次取货是在 2 个多月前,但无法弄清楚如何StatusID只为那些取货和更改ClientID。任何想法如何做到这一点?

4

2 回答 2

1

试试这个查询

对于 SQL 服务器

update ClientS set StatusID=4
where ClientID= (select P.ClientID
from Pickup P
join Clients C on P.ClientID= C.ClientID
where WIC=0 and C.StatusID = 1 or WIC=0 and C.StatusID = 2
group by p.clientid 
having max(p.PickupDate) < DATEADD(month,-2,GETDATE()));

您的内部查询返回 1 行的多个列,您仅将其与 clientId 进行比较,这就是您没有得到所需结果的原因。

于 2013-02-26T03:33:30.210 回答
1

尝试这个

update C
set StatusID=4
from (SELECT P.ClientID, MAX(p.PickupDate) MaxPickupDate
      FROM @Pickup P
      group by P.Clientid) P
     join @Clients C on P.ClientID= C.ClientID
where C.WIC=0 and C.StatusID in (1, 2)
      AND P.MaxPickupDate<DATEADD(month,-2,GETDATE())

另外,你这里有错误

where WIC=0 and C.StatusID = 1 or WIC=0 and C.StatusID = 2

对于 WIC=0 的任何行,此条件都将成立,您可以通过这种方式进行更正

WHERE WIC=0 AND C.StatusID in (1,2)
于 2013-02-26T03:37:55.320 回答