2016-05-12 94 views
0

我有一個劃分銷售按國家的數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

因此,大家可以看到,在價格帶< 20在英國順序號是50,而該單位平均爲2。正如我所說早些時候,我想要20以下的所有訂單的平均單位(圖中爲50)。

更清楚了嗎?

在此先感謝。

編輯:

enter image description here

第一個表:假設它是源

而第二個表得到平均,這就是我所追求的。

+3

你能分享一下你想要得到的樣本數據結果嗎?理解你想要做的事情有點難。 – Mureinik

+0

另外p.Id = c.Id和p.ID = s.ID確實有意義,FK在哪裏? – Ako

+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)

+0

乾杯。多數民衆贊成在我之前,但我想知道如果theres更簡單的方式,謝謝。 – Faiz