通过让 count = 1 更新基于 where group 的列

Update column based on where group by having count = 1

我希望使用 PledgeId 或任何内容更新空白列以填充我创建的要更新的新列。

我想更新字段。我尝试了很多不同的方法来更新字段。

我正在使用的代码缩小了我正在寻找的范围,但由于不同的错误似乎无法用它更新字段:

select IDPledge
from PledgePaymentSchedule
where DatePaid != ''
group by IDPledge
having count(IDPledge) = 1

我正在寻找 DatePaid 不为空的特定记录,按 IDPledge 分组,计数恰好为 1。意思是 一次 承诺。

许多不同尝试的最新变体:

Update [PledgePaymentSchedule] 
set [OneTimePledge] = 'Yes'
where exists
(SELECT count([IDPledge]) FROM [PledgePaymentSchedule]
where [DatePaid] !=  ''
group by [IDPledge]
having count([IDPledge]) = 1)

这会使用 'Yes' 更新所有记录,而不仅仅是从 where exists 语句中提取的 26 条记录。


Update s
set [OneTimePledge] = (SELECT distinct count(*)         FROM [PledgePaymentSchedule]
group by [IDPledge]
having count([IDPledge]) > 1)
FROM [PledgePaymentSchedule] s
where [DatePaid] !=  ''

此方差引发错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

最终我需要一个更新语句,用顶部的 select 语句的结果更新列 [OneTimePledge]。

谢谢!

如果我没看错,你想要创建一个标志,表明某些 IDPledge 有一个(且只有一个)有效的 DatePaid 值。

如果是这样,我建议使用通用 Table 表达式 (CTE) 来帮助您构建更新语句:

WITH
UpdateJoin AS
(
    SELECT
        OneTimePledge
    FROM
        PledgePaymentSchedule
    WHERE
        IDPledge IN
        (
            select IDPledge
            from PledgePaymentSchedule
            where DatePaid != ''
            group by IDPledge
            having count(IDPledge) = 1
        )
)
UPDATE
    UpdateJoin
SET
    OneTimePledge = 'Yes';

使用 CTE 隔离要更新的行通常会有所帮助。