根据SQL Server中另一个列值的条件返回更新的列值

时间:2017-10-01 16:33:04

标签: sql sql-server tsql date self-join

我有一个表Referrals,其中包含以下列:

  • ref_id
  • referrer_id(same as profile id)
  • referrer_bonus_amount
  • referral_valid
  • valid_from
  • valid_till

我需要编写代码来延长一个月内提交两次以上的租户的valid_till日期。所引用的数量可以通过列profile_id中特定数字(referrer_id)的出现次数计算(与个人资料ID相同)。以下两段代码正在单独完成工作,但我不知道如何加入它们以获得所需的结果。

select DATEADD(mm, 1, valid_till)
from Referrals

select 
    [referrer_id(same as profile id)], 
    count([referrer_id(same as profile id)]) 
from referrals
group by [referrer_id(same as profile id)]
having count([referrer_id(same as profile id)]) > 2

2 个答案:

答案 0 :(得分:1)

您可以使用in运算符:

SELECT DATEADD(MM, 1, valid_till) 
FROM   referrals
WHERE  referrer_id IN (SELECT   referrer_id
                       FROM     referrals
                       GROUP BY referrer_id
                       HAVING   COUNT(*) > 2)

或者如果您确实需要更新表而不只是查询添加的月份,您可以在update语句中使用相同的想法:

UPDATE referrals 
SET    valid_till = DATEADD(MM, 1, valid_till) 
WHERE  referrer_id IN (SELECT   referrer_id
                       FROM     referrals
                       GROUP BY referrer_id
                       HAVING   COUNT(*) > 2)

答案 1 :(得分:0)

我认为您可以使用join执行此操作。但是,我不确定表之间匹配的具体条件是什么:

select DATEADD(month, 1, valid_till)
from Referrals r join
     (select [referrer_id(same as profile id)], count([referrer_id(same as profile id)]) 
      from referrals
      group by [referrer_id(same as profile id)]
      having count([referrer_id(same as profile id)]) > 2
     ) rr
     on rr.ref_id = [referrer_id(same as profile id)];