2013-06-29 66 views
0

以下是我的查詢給我結果的相應值的總和。我如何計算每列預期ID的平均值?來自sql表的評論者的平均得分

Select 
    count(StoreId) as TotalReview, 
    sum(Case OnTimeDelivery when 'Within Time' then 1 else 0 end) as OnTimeDeliveryWithinTime, 
    sum(Case OnTimeDelivery when 'Little Delay' then 1 else 0 end) as OnTimeDeliveryLittleDelay, 
    sum(Case OnTimeDelivery when 'Excess Delay' then 1 else 0 end) as OnTimeDeliveryExcessDelay, 
from 
    StoreReviews 
where 
    StoreId = 1 

回答

0

您需要使用GROUP BY條款

SELECT storeId, COUNT(ontimedelivery), AVG(<column>) 
FROM storereviews 
WHERE storeid=1 
GROUP BY ontimedelivery 
+0

我試着按你給出的解決方案,但在返回AVG「0」。見下面的查詢。 SELECT storeId,COUNT(storeid),AVG(Case OnTimeDelivery'When Time'時1 then 0 end) FROM storereviews GROUP BY storeid – Vicky

+0

抱歉有錯誤。目前還不清楚你在平均採用什麼 – Sklivvz

+0

我希望OnTimeDelivery在'時間內'的人的比例等等。 – Vicky

0

你可以得到SUM根據您自己的查詢每家商店,但你必須添加GROUP BY,如:

SELECT Storeid, COUNT(StoreId) as TotalReview, 
SUM(Case OnTimeDelivery WHEN 'Within Time' THEN 1 ELSE 0 END) as OnTimeDeliveryWithinTime, 
SUM(Case OnTimeDelivery WHEN 'Little Delay' THEN 1 ELSE 0 END) as OnTimeDeliveryLittleDelay, 
SUM(Case OnTimeDelivery WHEN 'Excess Delay' THEN 1 ELSE 0 END) as OnTimeDeliveryExcessDelay 
FROM StoreReviews 
GROUP BY Storeid 

現在,如果你想得到的平均不是爲每個商店,而是爲所有商店基於OnTimeDelivery你是否Within TimeLittle DelayExcess Delay可以使用AVG這樣的:

SELECT CONVERT(Decimal(5,2),AVG(CAST(TotalReview as float))) as AvgTotal, CONVERT(Decimal(5,2),AVG(CAST(OnTimeDeliveryWithinTime as float))) as AvgWithinTime, CONVERT(Decimal(5,2),AVG(CAST(OnTimeDeliveryLittleDelay as float))) as AvgLittleDelay, CONVERT(Decimal(5,2),AVG(CAST(OnTimeDeliveryExcessDelay as float))) as AvgExcessDelay 
FROM (
SELECT Storeid, COUNT(StoreId) as TotalReview, 
SUM(Case OnTimeDelivery WHEN 'Within Time' THEN 1 ELSE 0 END) as OnTimeDeliveryWithinTime, 
SUM(Case OnTimeDelivery WHEN 'Little Delay' THEN 1 ELSE 0 END) as OnTimeDeliveryLittleDelay, 
SUM(Case OnTimeDelivery WHEN 'Excess Delay' THEN 1 ELSE 0 END) as OnTimeDeliveryExcessDelay 
FROM StoreReviews 
GROUP BY Storeid 
) StoreAverages 

見我Fiddle Demo