如何一对多查询多列的SUM

时间:2017-12-19 13:01:38

标签: sql sql-server

我有以下表格:

| Sales.Transaction
| ---------------
| Id
| Date
| BranchId
| Commission
|----------------


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


| Sales.Branch
|-------------
| Id
| Name
|-------------

如何获得total sales of each Branchestotal number of transactionstotal pages?我需要有这样的数据形状:

注意Total amount of Transaction, can be computed by getting the sum of TransactionItems(Rate * Pages) - Commission

| Branches   | Total Sales | No. of Transactions | Total Pages      |
| Branch A   | 10,500      | 14                  |       17         |
| Branch B   |  5,200      |  4                  |        4         |
| Branch C   |    400      |  2                  |        2         |
| Branch D   |  6,100      |  8                  |       14         |

我的查询存在的问题是,当Transaction有一个Commission且多个TransactionItems时,Commission会乘以{{1}的数量}}

TransactionItems

1 个答案:

答案 0 :(得分:1)

这很棘手 - 我认为解决方案是在将其余表连接在一起之前聚合事务项:

select b.Name as BranchName,
       count(t.Id) as Transactions,
       sum(ti.total_minus_commission) - SUM(t.Commission) as TotalSales,
       sum(ti.total_pages) as Pages
from Sales.Branch b left join
     Sales.[Transaction] t 
     on b.Id = t.BranchId and
        t.Date >= '2017-11-01'
        t.Date < '2017-12-01' left join
     (select ti.TransactionId,
             sum(ti.Pages * ti.Rate) as total_minus_commission,
             sum(ti.Pages) as total_pages
      from Sales.TransactionItem ti
      group by ti.TransactionId
     ) ti
     on ti.TransactionId = t.Id
group by b.Name
order by b.Name ASC;

注意:我也认为这正确计算Transactions