2017-07-14 161 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