假设我有两个表
Customer
---
Id Name
1 Foo
2 Bar
和
CustomerPurchase
---
CustomerId, Amount, AmountVAT, Accountable(bit)
1 10 11 1
1 20 22 0
2 5 6 0
2 2 3 0
我需要一个单记录每个已加入和分组的Customer和CustomerPurchase组。每个记录都包含
- 列从表Customer
- 一些聚合函数,如SUM
- 一个'计算'列。例如其他列 的差异
- CustomerPurchase表子查询结果
一个我想要得到的结果的例子
CustomerPurchases
---
Name Total TotalVAT VAT TotalAccountable
Foo 30 33 3 10
Bar 7 9 2 0
我能够得到一个单一的行只有通过分组所有常见的列,我不认为这是正确的方式去做。另外,我不知道如何做"VAT"列和"TotalAccountable"列,它只过滤掉CustomerPurchase的某些行,然后在结果上运行某种聚合函数。下面的例子不工作,但我想展示我想要实现的
select C.Name,
SUM(CP.Amount) as 'Total',
SUM(CP.AmountVAT) as 'TotalVAT',
diff? as 'VAT',
subquery? as 'TotalAccountable'
from Customer C
inner join CustomerPurchase CR
on C.Id = CR.CustomerId
group by C.Id
我建议您只需要对您的查询进行以下轻微更改。如果可以的话,我也会考虑清楚,使用术语净额和毛额,这是典型的不包括增值税的价格。
select c.[Name],
Sum(cp.Amount) as Total,
Sum(cp.AmountVAT) as TotalVAT,
Sum(cp.AmountVAT) - Sum(CP.Amount) as VAT,
Sum(case when cp.Accountable = 1 then cp.Amount end) as TotalAccountable
from Customer c
join CustomerPurchase cp on cp.CustomerId = c.Id
group by c.[Name];