mysql group by和非零值的平均值

时间:2013-09-16 08:52:54

标签: mysql

我有一张表格如下

carrier   duration   date
a         10         05-09-2013 
a         0          04-09-2013 
b         1          05-09-2013 
b         3          04-09-2013  
c         2          05-09-2013 
c         3          04-09-2013

我想根据承运人和总持续时间来计算平均值

结果应该是:

carrier a = avg is 10
carrier b = avg is 2
carrier c = ave is 2.5

它应该计算非零值的总持续时间,因此对于承运人A,因为它在04-09-2013日期有任何活动,那么平均值应为10/1,即总持续时间/非日期数零持续时间)

3 个答案:

答案 0 :(得分:1)

select                  
  carrier,           -- carrier column in result set
  avg(duration)      -- average duration column in result set
from tablename       -- specify what table to get results from
where duration>0     -- condition excluding table rows where duration=0
group by carrier;    -- All rows with the same 'carrier' value are grouped 
                     -- together into one row in the result set. This works with 
                     -- the aggregate function avg();

答案 1 :(得分:0)

select carrier, avg(duration) 
from mytable
where duration > 0
group by carrier

答案 2 :(得分:0)

select carrier,AVG(duration) as average_duration
from tablename
where duration != 0
group by carrier