如何在ms-access中使用更新查询来计算另一个表中的特定值?

时间:2019-05-17 11:10:29

标签: sql ms-access

我正在使用ms-access,并且我有两个这样的表:

tbl1: contract

| c_ssn | m_ssn | termination |
===============================
|   1   |   1   |      Y      |
|   2   |   2   |      N      |
|   3   |   1   |      Y      |

tbl2: member

| m_ssn | count |
=================
|   1   |       |
|   2   |       |

我想计算[终止]的值是按[m_ssn]分组的“ Y”的[合同]的行数。因此所需的结果将是这样的:

tbl2: member

| m_ssn | count |
=================
|   1   |   2   |
|   2   |   0   |

为此,我尝试了以下sql代码:

update member
set count =
(select count(*) from contract
where contract.m_ssn = member.m_ssn & contract.termination = "Y")

但是此代码会产生错误:“操作必须是可更新的查询。” 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

您在要使用布尔值AND的地方使用字符串连接:

update member
set count = (select count(*)
             from contract
             where contract.m_ssn = member.m_ssn and
                   contract.termination = "Y"
            );

答案 1 :(得分:0)

尝试使用条件聚合:

SELECT
    m.m_ssn,
    SUM(IIF(c.termination = 'Y', 1, 0)) AS count
FROM member m
LEFT JOIN contract c
    ON m.m_ssn = c.m_ssn
GROUP BY
    m.m_ssn;

请注意,建议您不要进行更新,因为每次contract表中的数据更改时,您都必须再次进行更新。如果这是一次事件,则IMO进行更新才有意义。

答案 2 :(得分:0)

这是在Access中执行多表更新的最常见方法。

UPDATE member AS A
INNNER JOIN contract AS B ON A.m_ssn = B.m_ssn 
SET A.count = Count(B.termination)
WHERE B.termination = "Y"