Sql 计数联接表

Sql 计数联接表,sql,sql-server,Sql,Sql Server,我有两个表tblFuneralHomes和tblFuneralTransactions。一个表可能有许多事务。我需要返回用户的殡仪馆并计算交易,但如果殡仪馆没有交易,则不会在结果中返回 Select tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key, count(tft.id) as counts from tblFuneralHomes tfh inner join tblFuneralTransactions tf

我有两个表
tblFuneralHomes
tblFuneralTransactions
。一个表可能有许多事务。我需要返回用户的
殡仪馆
并计算交易,但如果殡仪馆没有交易,则不会在结果中返回

Select tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key, count(tft.id) as counts from tblFuneralHomes tfh
inner join tblFuneralTransactions tft on tft.funeral_home_guid = tfh.funeral_home_guid where (tft.canceled=0 and tft.completed=0)
and tfh.funeral_home_guid in (select funeral_home_guid 
from tblDirectorHomes
where director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b') 
group by tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key
这是没有连接的结果

我知道当前用户有3个
殡仪馆

但当我加入交易并计算时,其中一个家庭没有交易,也没有显示


您必须使用
左连接
而不是
内部连接
,因此
tblFuneralHomes
的所有记录都被记录下来:

SELECT tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key, COUNT(tft.id) AS counts 
FROM tblFuneralHomes tfh LEFT JOIN tblFuneralTransactions tft ON tft.funeral_home_guid = tfh.funeral_home_guid 
WHERE (tft.funeral_home_guid IS NULL OR (tft.canceled = 0 AND tft.completed = 0))
    AND tfh.funeral_home_guid IN (
        SELECT funeral_home_guid 
        FROM tblDirectorHomes
        WHERE director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b'
    )
GROUP BY tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key
您正在使用
WHERE
条件下的
tblFuneralTransactions
列。如果
tblFuneralHomes
的记录没有
tblFuneralTransactions
则(不可用)
tblFuneralTransactions
记录的所有列值均为
NULL
。因此,以下条件为假:
tft.cancelled=0和tft.completed=0

要包含
tblFuneralHomes
的所有记录,您需要允许
tblFuneralTransactions
的列为
NULL
。所以你必须替换这个条件

(tft.canceled = 0 AND tft.completed = 0)
以下

(tft.funeral_home_guid IS NULL OR (tft.canceled = 0 AND tft.completed = 0))

我建议您进行以下查询(对您的查询稍作修改):


我切换到
左加入
,因此不匹配的殡仪馆仍将包含在结果集中。此外,我还处理了其他表中相应的
nul
值:当它为null时,列应为0,否则为1。然后对这些值求和就足够了。

示例数据和预期输出将更有帮助。@SurajKumar一分钟的外部联接,而不是内部联接。我尝试了左联接和左外部联接,但得到了相同的结果。请查看更新(添加的
tft.fuller\u home\u guid为NULL
part)。再次尝试整个查询。我不知道为什么,但仍然没有得到所有的房子。如果我删除where(tft.completed=0和tft.canceled=0),我将获得所有具有计数的home。您需要允许空值-请参阅解释完成。非常感谢。
Select tfh.funeral_home_guid, 
       tfh.funeral_home_name, 
       tfh.reference_key, 
       sum(case when tft.id is null then 0 else 1 end) as counts 
from tblFuneralHomes tfh
left join tblFuneralTransactions tft on tft.funeral_home_guid = tfh.funeral_home_guid 
where (tft.canceled=0 and tft.completed=0)
  and tfh.funeral_home_guid in (select funeral_home_guid 
                                from tblDirectorHomes
                                where director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b') 
group by tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key