我想用符合COUNT
标准的表2中的所有记录,为与表1中的主键匹配的每条记录WHERE
。例如,
SELECT Table1.PrimaryID, Table1.Address, COUNT(Table2.Tenants)
FROM Table2 LEFT JOIN Table1 ON Table2.ForeignID = Table1.PrimaryID
WHERE (Table2.Status = "Single")
GROUP BY Table1.PrimaryID, Table1.Address
但是,如果没有匹配的记录,SQL将不返回任何内容。我尝试过Nz
函数,该函数可以用指定的值替换Null值,但是如果没有任何条件满足其条件,则WHERE
子句不会返回Null。
作为一种变通方法,我放弃了WHERE
子句,而推荐使用SUM
和IIF
语句:
SELECT Table1.PrimaryID, Table1.Address, SUM(IIF(Table2.Tenants="Single",1,0))
FROM Table2 LEFT JOIN Table1 ON Table2.ForeignID = Table1.PrimaryID
GROUP BY Table1.PrimaryID, Table1.Address
我的解决方法是否适合我的情况?在COUNT
和WHERE
子句情况下,是否有其他选择可返回0值?谢谢!
答案 0 :(得分:2)
您可以使用子查询来计算计数:
SELECT Table1.PrimaryID, Table1.Address, (SELECT Count(*) FROM Table2 WHERE Table2.ForeignID = Table1.PrimaryID AND Table2.Tenants="Single") As CountOfTable2
FROM Table1
GROUP BY Table1.PrimaryID, Table1.Address
如果Table1.PrimaryID对于表1唯一,则可以删除分组依据。
根据其他情况,您的Sum(Iif(
方法可能更好。如果要计算多个不同的条件,则可以使用该参数,因为这样可以避免编写多个子查询。
答案 1 :(得分:1)
您的第一个版本基本上是正确的,表格只是倒退:
SELECT Table1.PrimaryID, Table1.Address, COUNT(Table2.Tenants)
FROM Table1 LEFT JOIN
Table2
ON Table2.ForeignID = Table1.PrimaryID AND
Table2.Status = "Single"
GROUP BY Table1.PrimaryID, Table1.Address
说实话,我不确定MS Access是否支持此ANSI标准构造。可以使用子查询轻松调整它:
SELECT Table1.PrimaryID, Table1.Address, COUNT(Table2.Tenants)
FROM Table1 LEFT JOIN
(SELECT Table2.*
FROM Table2
WHERE Table2.Status = "Single"
) as table2
ON Table2.ForeignID = Table1.PrimaryID
GROUP BY Table1.PrimaryID, Table1.Address