来自sql表的审阅者的平均得分

时间:2013-06-29 08:40:25

标签: sql sql-server-2008

以下是我的查询,给出了相应值之和的结果。如何计算每列预期Id的平均值?

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

2 个答案:

答案 0 :(得分:0)

您需要使用GROUP BY子句

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

答案 1 :(得分: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

现在,如果您希望平均值不是针对每个商店,而是针对所有商店并且基于OnTimeDeliveryWithin Time或{ {1}}或Little Delay您可以像这样使用Excess Delay

AVG

查看我的Fiddle Demo