我想获得平均值
我有下表:
| ClientName | MemberName | TotalAmountSpent | PercentAmountSpent|
|-----Palace--- |---------John---- |-----------376.26------ |------------???------------ |
|-----Palace--- |--------Adem---- |-----------646.83------ |------------???------------ |
|----Pizzeria--- |---------Zoey----- |-----------10.00-------- |------------???------------ |
这是我到目前为止所做的:
SELECT c.ClientName
,m.Mem_Name
,Sum(mv.AmountSpent) as TotalAmountSpent
,Sum(mv.AmountSpent)/ *100 as PercentAmountSpent
FROM Client c
JOIN MemberVisits mv
On c.ClientId = mv.RestaurantId
JOIN Member m
On m.Mem_ID = mv.MemberId
GROUP by ClientName, m.Mem_Name
ORDER by ClientName
公式为:(Total Amount Spent / total business sales) * 100
例如:johns percentamountspent应为(376.26/ (376.26 + 646.83)) * 100
如何修复此行Sum(mv.AmountSpent)/ /*Something here */ *100 as PercentAmountSpent
以获得正确的输出?
由于
答案 0 :(得分:1)
你可以这样做:
http://sqlfiddle.com/#!6/cf953/4
create table test (ClientName varchar(50), MemberName varchar(50), TotalAmountSpent float)
insert into test (ClientName, MemberName, TotalAmountSpent)
select 'Palace', 'John', 376.26
union all select 'Palace', 'Adem', 646.83
union all select 'Pizzeria', 'Zoey', 10
select t.ClientName,
t.MemberName,
t.TotalAmountSpent,
(t.TotalAmountSpent / groupedClientName.totalAmountSpent * 100) as percentAmountSpent
from test t
inner join (
-- this subquery is used to get the total amount per "Client", which then can be used in the outer query to get a per member contribution percent
select ClientName, sum(totalAmountSpent) as totalAmountSpent
from test
group by ClientName
) groupedClientName on t.ClientName = groupedClientName.ClientName
答案 1 :(得分:0)
您可以使用子查询(以避免在计算中使用多个SUM),并使用另一个子查询上的内部联接来获取totalBusinessSales(看起来像是RestaurantId的amountSpent之和)
select
ClientName
MemName,
totalAmountSpent,
sumAmountSpent / totalBusinessSales * 100 as percentAmountSpent
from
(select c.ClientName,
m.Mem_Name,
sum(mv.AmountSpent) as totalAmountSpent,
sum(s.TotalBusinessSales) as totalBusinessSales
from Client c
join MemberVisits mv on c.ClientId = mv.RestaurantId
join Member m on m.Mem_ID = mv.MemberId
join (select RestaurantId, sum(amountSpent) as TotalBusinessSales
from MemberVisits
group by RestaurantId) s
on s.RestaurantId = c.ClientId
group by t.ClientName, m.Mem_Name) i
没有第一级子查询,你会有
select c.ClientName,
m.Mem_Name,
sum(mv.AmountSpent) as totalAmountSpent,
sum (mv.AmountSpent) / sum(s.TotalBusinessSales) * 100 as percentAmountSpent
from Client c
join MemberVisits mv on c.ClientId = mv.RestaurantId
join Member m on m.Mem_ID = mv.MemberId
join ( select RestaurantId, sum(amountSpent) as TotalBusinessSales
from MemberVisits
group by RestaurantId) s
on s.RestaurantId = c.ClientId
group by t.ClientName, m.Mem_Name