SQL百分比组

时间:2017-07-14 14:39:57

标签: sql sql-server

我需要快速报告员工演示者及其客户教室出勤率,并且我试图在SQL中找出正确的查询(对于SQL Server)。

客户端是针对类单独安排的,因此在表tSchedule中,每一行都有一个类名,类的时间和日期,客户端名称,类主持人的名称以及客户端的名称。出勤状态(例如,'现在'缺席'缺席'缺席','迟到'等等。)

所以我需要一个SQL查询,它将为每个演示者输出一行,其中包含在给定日期范围内在该演示者类中安排的客户端总数,即实际显示的总数(即出席状态为“出席状态”或“缺席出借”(#);以及出现或出现的总数的百分之几"客户代表。

在下面的每个回复中添加一些细节:

tSchedule

class            class_date     Employee_id     client_id       attendance_status
Basket Weaving   2017-07-13     231             712             Present
Basket Weaving   2017-07-13     231             121             Present
Basket Weaving   2017-07-13     231             186             Absent
Basket Weaving   2017-07-13     231             666             Absent
Juggling         2017-07-13     900             111             Present
Juggling         2017-07-13     900             222             Present
Juggling         2017-07-13     900             333             Present
Juggling         2017-07-13     900             712             Absent w/Excuse



Expected Result of Query:

Employee_id Clients Scheduled   Clients Present or Excused  Attendance Rate
231         4                   2                           50%
900         4                   4                           100%

(附录)  好吧,我最终使用(下面)的查询有效,但它很难看,我确定不理想。如果有人知道获得相同结果的最优雅方式,我会非常感激。 (@ param1和@param2是用户输入的日期,表示所需时间跨度的开始和结束日期)

Select
   pl.emp_id
   ,e.last_name + ', ' + e.first_name as facilitator
   ,count(pl.emp_id) as total_Count
   ,(select count(*) from planner where emp_id = pl.emp_id
       and visit_status in ('ARRIVED', 'PRESENT WITH JS', 'PRESENT NO JS')
       and plan_date >= @param1
       and plan_date <= @param2) as attended_Count
   ,cast(cast((select count(*) from planner where emp_id = pl.emp_id
       and visit_status in ('ARRIVED', 'PRESENT WITH JS','PRESENT NO JS')
       and plan_date >= @param1
       and plan_date <= @param2) as float) / cast((select count(*) from
       planner where emp_id = pl.emp_id
       and plan_date >= @param1
       and plan_date <= @param2) as float) * 100 as decimal (18,2)) as attendance_percent
from planner pl inner join employees e on pl.emp_id = e.emp_id
where pl.program_id = 2
    and pl.visittype_id in (42,173)
    and plan_date >=@param1
    and plan_date <= @param2
group by pl.emp_id, e.last_name + ', ' + e.first_name

1 个答案:

答案 0 :(得分:0)

select
    status,
    cnt*100.0/total
from 
(select c status,count(*) cnt from attendance c group by c.status),
(select count(*)total from attendance c)