Left Join 和 Group By 可能有空行

Left Join and Group By with possible empty row

我有这些表

`Sales.Branch`
-Id
-Name
        ==Rows in Sales.Branches==
         - Al Ain
         - Chamber
         - Hamdan
         - Mina
         - Marina
         - EMTI

`Sales.Transaction`

- Id
- Date
- BranchId

`Sales.TransactionItem`
- Id
- TransactionId
- Pages
- Rate

我想得到他们 total SalesTotalPagesNo. OF Transaction 关于特定 StartEnd Dates 的报告。

我试过这个查询,但它只 returns 在指定日期有交易的分支机构。

select
    b.Name as BranchName,
    COUNT(t.Id) as Transactions,
    SUM(ti.Pages * ti.Rate) as TotalSales,
    SUM(ti.Pages) as Pages

    from 
        Sales.[Transaction] t
            left join Sales.TransactionItem ti
            on ti.TransactionId = t.Id
            left join Sales.Branch b on b.Id = t.BranchId
    where t.Date >= '2016-01-01'
AND t.Date <= '2016-02-01'
    group by b.Name
    order by b.Name ASC

由于 EMTI 分支在 2016-01-01 上没有交易,直到 2016-02-01 它才不包含在结果中。

我想要的是包括 ALL 分支,即使它们没有交易,而是在 TotalSales, TotalPAges, Transactions 上显示 0

以Branch为主table加入条件:

select
    b.Name as BranchName,
    COUNT(t.Id) as Transactions,
    SUM(ISNULL(ti.Pages, 0) * ISNULL(ti.Rate, 0)) as TotalSales,
    SUM(ISNULL(ti.Pages, 0)) as Pages
from 
    Sales.Branch b
        left join Sales.[Transaction] t 
            on b.Id = t.BranchId 
            and t.Date >= '2016-01-01'
            AND t.Date <= '2016-02-01'
        left join Sales.TransactionItem ti
            on ti.TransactionId = t.Id
group by b.Name
order by b.Name ASC

请 select 来自分支 table 的数据作为父 table 并检查 isnull

select
b.Name as BranchName,
COUNT(ISNULL(t.Id,0)) as Transactions,
SUM(ISNULL(ti.Pages,0) * ISNULL(ti.Rate,0)) as TotalSales,
SUM(ISNULL(ti.Pages,0)) as Pages

from Sales.Branch b 
    left join  Sales.[Transaction] t on b.Id = t.BranchId
        left join Sales.TransactionItem ti
        on ti.TransactionId = t.Id
where t.Date >= '2016-01-01'
AND t.Date <= '2016-02-01'
group by b.Name
order by b.Name ASC