Left Join和Group By可能为空行

时间:2016-01-31 11:40:00

标签: sql-server tsql join group-by left-join

我有这些表

`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 SalesTotalPages No. OF Transaction上收到关于StartEndDates的报告。

我已经尝试过这个查询,但它只返回在指定日期有交易的分支。

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

enter image description here

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

我想要的是包括所有分支,即使他们没有交易,也会在0上显示TotalSales, TotalPAges, Transactions

2 个答案:

答案 0 :(得分:2)

使用Branch作为主表并按时加入条件:

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

答案 1 :(得分:0)

请从分支表中选择数据作为父表并检查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