如何在子查询中使用“分组依据”?

时间:2019-08-12 10:27:36

标签: sql group-by subquery

我想找到一种状态下每个驱动程序ID的百分比(在此示例中为“ isDriving”)。这是我的数据集:

(id, duration, state, driverid) VALUES ('1', '3000', 'isDriving', 'b65');

(id, duration, state, driverid) VALUES ('1', '2500', 'isDriving', 'b65');

(id, duration, state, driverid) VALUES ('1', '500', 'isIdling', 'b65');

(id, duration, state, driverid) VALUES ('1', '5500', 'isIdling', 'b65');

(id, duration, state, driverid) VALUES ('1', '300', 'isDriving', 'b34');

(id, duration, state, driverid) VALUES ('1', '200', 'isIdling', 'b34');

(id, duration, state, driverid) VALUES ('1', '200', 'isDriving', 'b15');

(id, duration, state, driverid) VALUES ('1', '500', 'isIdling', 'b15');

我已经尝试过以下查询:

select driverid, 
    (sum(duration) / (select sum(duration) from table_name1 group by driverid)) * 100 as percent
from table_name1 
where state='isDriving' 
group by driverid

我希望这样的输出:

------------------
driverid  percent |
------------------
b65         50    |
b34         60    |
b15         28.6  |

但向我显示:子查询返回的行多于1

1 个答案:

答案 0 :(得分:1)

有条件聚合:

select 
  driverid,
  round(100.0 * sum(case when state = 'isDriving' then duration else 0 end) / sum(duration), 1) percent    
from tablename
group by driverid;

请参见Wikipedia
结果:

| driverid | percent |
| -------- | ------- |
| b15      | 28.6    |
| b34      | 60      |
| b65      | 47.8    |