我有一个表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
答案 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)];