我正在尝试获取SQL中比率的平均值。
我的表格如下:
T_TOTAL | NUM_ASSETS
----------------------
32 | 8
20 | 4
24 | 4
所以我所追求的价值 5 ,如:
T_TOTAL | NUM_ASSETS | T_TOTAL/NUM_ASSETS
---------------------------------------------
32 | 8 | 4
20 | 4 | 5
24 | 4 | 6
-------------------
AVG = 5
到目前为止,我有这个,但它不起作用:
SELECT T_TOTAL As Time, NUM_ASSETS As Assets,
Time/Assets As TimePerAsset, AVG(TimePerAsset) As Result
FROM MATCHES
有什么想法吗?
答案 0 :(得分:3)
SELECT t.*,
Result = AVG(TimePerAsset)
FROM (
SELECT [Time] = T_TOTAL,
[Assets] = NUM_ASSETS,
[TimePerAsset] = CASE WHEN NUM_ASSETS <> 0
THEN T_TOTAL/NUM_ASSETS
ELSE NULL
END
FROM MATCHES
) t
答案 1 :(得分:2)
select avg(t_total/num_assets) from matches
如果num_assets中有0,则可以避免除以0,如下所示:
select avg(t_total/nullif(num_assets, 0)) from matches
答案 2 :(得分:1)
SELECT M.Time, M.Assets, M.TimePerAsset, Avg(M.TimePerAsset) as AvgTimePerAsset
FROM
(
SELECT T_TOTAL As TotalTime
, NUM_ASSETS As Assets
, CASE WHEN NUM_ASSETS <> 0 THEN T_TOTAL/NUM_ASSETS ELSE NULL END As TimePerAsset
FROM Matches
) M
GROUP BY M.Time, M.Assets, M.TimePerAsset
答案 3 :(得分:0)
你可以试试这个
SELECT T_TOTAL As Time, NUM_ASSETS As Assets,
case when Assets <> 0 then Time/Assets end As TimePerAsset, AVG(case when Assets <> 0 then Time/Assets end) As Result
FROM MATCHES