In an Access database, TableA has a foreign key to TableB. TableB contains a column with four possible values. I need to count the number of rows in TableA for one of the four values in TableB. This was my initial attempt:
SELECT COUNT(*) As TableACount
FROM TableA
INNER JOIN TableB ON TableA.fk_tableB = TableB.pk_tableB
WHERE TableB.[value] = 1
Here's another attempt:
SELECT COUNT(*) As TableACount,
TableB.[value]
FROM TableA
INNER JOIN TableB ON TableA.fk_tableB = TableB.pk_tableB
WHERE TableB.[value] = 1
GROUP BY TableB.[value]
The result returned in both queries appears to be the number of TableA rows times the number of TableB rows they are joined to. How can I get just the number of TableA rows?
You may either use a distinct count:
SELECT COUNT(DISTINCT a.pk_tableA) AS TableACount
FROM TableA a
INNER JOIN TableB b
ON a.fk_tableB = b.pk_tableB
WHERE b.[value] = 1;
Or, use exists logic:
SELECT COUNT(*) AS TableACount
FROM TableA a
WHERE EXISTS (SELECT 1 FROM TableB b WHERE b.pk_tableA = a.fk_tableB AND b.[value] = 1);
SELECT COUNT(*) As TableACount,
TableA.fk_tableB
FROM TableA
INNER JOIN TableB ON TableA.fk_tableB = TableB.pk_tableB
WHERE TableB.[value] = 1
GROUP BY TableA.fk_tableB
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.