你可以得到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 Delay
或Excess 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
我試着按你給出的解決方案,但在返回AVG「0」。見下面的查詢。 SELECT storeId,COUNT(storeid),AVG(Case OnTimeDelivery'When Time'時1 then 0 end) FROM storereviews GROUP BY storeid – Vicky
抱歉有錯誤。目前還不清楚你在平均採用什麼 – Sklivvz
我希望OnTimeDelivery在'時間內'的人的比例等等。 – Vicky