查找,分组并计算加权平均值?

时间:2018-07-06 20:29:35

标签: sql-server sql-server-2008 tsql

我没有更好的头衔,所以去。

我有一个查询表,向我显示了每个CityId与每个商店之间的距离。例如,第一行告诉我H1Eagle 2.5英里。它仅显示H部分,但在CityId和存储之间具有每种可能的组合:

declare @stores table 
(
    CityId varchar(10),
    miles decimal(8,2),
    store varchar(30)
)
insert into @stores

select 'H1',2.5, 'Eagle' union
select 'H1',3.5, 'Sears' union
select 'H1',2.0, 'BK' union
select 'H2',2.0, 'Eagle' union
select 'H2',1.5, 'Sears' union
select 'H2',1.8, 'BK' union
select 'H3',0.1, 'Eagle' union
select 'H3',0.5, 'Sears' union
select 'H3',0.7, 'BK'

这是数据表。它有多少商店离开了每个部分:

declare @gone table
(
    City varchar(10),
    CityId varchar(10),
    Outs int
)
insert into @gone 
select 'Houston', 'H1', 6  union 
select 'Houston','H2', 4  union
select 'Houston', 'H3', 1  union
select 'Miami', 'M1', 12  union
select 'Miami', 'M2', 10  union
select 'Miami', 'M3', 18 union
select 'Miami', 'M4', 15

要获得weighted averageEagle的{​​{1}},我必须得到休斯顿所在城市的所有行,将Houston乘以距离,然后除以所有@gone.Outs的总和。

对于Outs组合,应为:

  

[(((H1到Eagle)* 6)+((H2到Eagle)* 4)+((H3到Eagle)* 1)] /(H1出+ H2出+ H3出)

这是:

  

(((2.5 * 6)+(2.0 * 4)+(0.1 * 1))/(4 + 6 + 1)= 2.1('Eagle')

对于Houston - Eagle组合,应为:

  

[(((H1至Sears)* 6)+((H2至Sears)* 4)+((H3至Sears)* 1)] /(H1输出+ H2输出+ H3输出)

这是:

  

(((6 * 3.5)+(4 * 1.5)+(1 * 0.5))/(4 + 6 + 1)= 2.5('Sears')

与迈阿密一样,这是同一件事:

  

[(((M1至Sears)* 6)+((M2至Sears)* 4)+((M3至Sears)* 1)+((M4至Sears)* 1)] /(M1 Out + M2输出+ M3输出+ M4输出)

结果应如下所示:

Houston - Sears

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这应该有效:

select g.City, s.Store, sum(s.miles * g.Outs)/sum(g.Outs) as [Avg]
from @gone g
inner join @stores s on g.CityId = s.CityId
group by g.City, s.store

答案 1 :(得分:0)

仍然未经测试,但我认为这可以做到:

SELECT City, Store, 
  SUM(miles*outs)/(SELECT SUM(outs) FROM @gone g2 WHERE g2.CityID=s.CityID) AS WeightedAverage
FROM @stores s
INNER JOIN @gone g
  ON s.CityID=g.CityID
GROUP BY Store, CityID, City