计算联接表

时间:2019-03-29 10:45:15

标签: sql sql-server

我有两个表tblFuneralHomestblFuneralTransactions。一个表可能有许多事务。我需要返回用户的funeralHomes并计算交易次数,但是如果funeralHomes没有交易,则不会返回结果。

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

这是不加入enter image description here的结果

我知道当前有3个funeralHomes用户。

但是当我加入交易并计算在内时,其中一个房屋没有交易,也没有显示。

enter image description here

2 个答案:

答案 0 :(得分:3)

您必须使用LEFT JOIN而不是INNER JOIN,以便获取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

您在tblFuneralTransactions条件下使用WHERE列。如果tblFuneralHomes的记录没有tblFuneralTransactions,则tblFuneralTransactions记录的所有列值都是NULL。因此,以下条件为假:tft.canceled = 0 AND 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))

答案 1 :(得分:2)

我建议以下查询(对查询的少量修改):

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

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

相关问题