根据结果​​集获取平均值列

时间:2016-05-12 09:23:50

标签: sql tsql

我有一个select语句,按国家/地区划分销售额,priceBanding(参见下面的示例)

enter image description here

select语句如下所示:

SELECT p.[Price Band]
,t.[Country]
,o.COUNT([Order]) as [Order Count]
FROM #price p (temp table)
INNER JOIN country t ON p.CountryCode = t.countryCode
INNER JOIN sales o ON o.salesValue >= p.startPrice and s.salesValue < p.endPrice

我希望能够做到的是基于这个结果我希望获得平均单位数,即对于所有低于20的订单,平均单位数是多少,对于所有其他单位数相同。我怎么能这样做?

它很可能很简单,但我无法通过它思考。

我在追求的是:

enter image description here

正如您所看到的,在英国的价格区间&lt; 20中,订单数量为50,平均单位为2.正如我之前提到的,我希望所有订单的平均值低于20 (图中为50)。

更清楚了吗?

提前致谢。

编辑:

enter image description here

第一个表:假设它是源

第二张表得到平均值,这就是我所追求的。

1 个答案:

答案 0 :(得分:0)

你不能只使用avg()吗?

SELECT p.[Price Band], t.[Country],
       o.COUNT(*) as [Order Count],
       AVG(Items)
FROM #price p INNER JOIN
     country t
     ON p.CountryCode = t.countryCode INNER JOIN
     sales o
     ON o.salesValue >= p.startPrice and s.salesValue < p.endPrice
GROUP BY p.[Price Band], t.[Country]
ORDER BY t.[Country], p.[Price Band] 

注意:SQL Server对整数进行整数除法(因此3/2 = 1而不是1.5),AVG()也是如此。使用小数点数更准确。一种简单的方法是使用AVG(items * 1.0)