I'm using ms-access, and I have two tables like this:
tbl1: contract
| c_ssn | m_ssn | termination |
===============================
| 1 | 1 | Y |
| 2 | 2 | N |
| 3 | 1 | Y |
tbl2: member
| m_ssn | count |
=================
| 1 | |
| 2 | |
I want to count the number of rows of [ contract ] that the value of [ termination ] is "Y" grouped by [ m_ssn ]. So the desired result will be like this:
tbl2: member
| m_ssn | count |
=================
| 1 | 2 |
| 2 | 0 |
To do this I've tried this sql code:
update member
set count =
(select count(*) from contract
where contract.m_ssn = member.m_ssn & contract.termination = "Y")
But this code make the error: "Operation must be an updateable query." How can I fix this problem?
You are using string concatenation where you want the boolean AND
:
update member
set count = (select count(*)
from contract
where contract.m_ssn = member.m_ssn and
contract.termination = "Y"
);
Try using conditional aggregation:
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;
Note that I recommend against doing the update, because every time the data in the contract
table changes, you will have to do the update again. IMO doing the update only makes sense if this is a one-time event.
This is the most common way to do multiple table update in 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.