我有以下表格:
| Sales.Transaction
| ---------------
| Id
| Date
| BranchId
| Commission
|----------------
| Sales.TransactionItem
| ------------------
| Id
| Rate
| Pages
| TransactionId
|-------------------
| Sales.Branch
|-------------
| Id
| Name
|-------------
如何获得total sales of each Branches
,total number of transactions
和total 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
答案 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
。