0

下面是我的查询,给出了相应值的总和。我如何计算每列期望 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
4

2 回答 2

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 Time可以这样使用:Little DelayExcess DelayAVG

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

看我的小提琴演示

于 2013-06-29T10:40:49.717 回答
0

您需要使用该GROUP BY子句

SELECT storeId, COUNT(ontimedelivery), AVG(<column>)
FROM storereviews
WHERE storeid=1
GROUP BY ontimedelivery
于 2013-06-29T08:53:21.997 回答