2017-07-14 147 views
-1

我需要提供员工演示者及其客户端课堂出勤率的快速报告,并且我试图找出SQL(针对SQL Server)中的正确查询。SQL Percentage Group By

客户端是单独安排的课程,所以在表tSchedule中,每一行都有一个类名,课程的时间和日期,客户端名称,课堂演示者的名字以及客户端的出席状态(例如'present ','缺席','缺席w /辩解','迟'等)

所以我需要一个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% 

(附录) 好吧,我已经结束了使用(如下图)作品的查询,但它的丑陋,我敢肯定不理想。如果有人知道获得相同结果的最优雅的方式,我非常感谢。 (@参数1和@ 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 >[email protected] 
    and plan_date <= @param2 
group by pl.emp_id, e.last_name + ', ' + e.first_name 
+4

添加样本数据,预期成果和查询你到目前为止已经试过 –

+2

这是一个伟大的地方开始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/您在这里有足够的代表来了解这个问题缺乏任何相关信息。 –

+1

请显示模式细节,一些示例数据,然后向我们展示您尝试的内容,这是学习的最佳方式。 –

回答

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) 
+0

为什么子查询?顺便说一句...你错过了别名。 – scsimon

+0

@scsimon:如果你可以做到没有子查询,请做出自己的答案。也许虽然OP已经在他们自己的尝试中编辑了这个问题......“:-)'。 – halfer

+0

@halfer此查询将失败...因为它不会运行。期。有多个语法问题。 – scsimon