2017-07-14 4 views
-1

従業員のプレゼンターとクライアントの教室出席率の簡単なレポートを提示する必要があります.SQL(SQL Server用)で正しいクエリを把握しようとしています。SQL Percentage Group

クライアントはクラスごとに個別にスケジュールされているため、テーブルtScheduleではすべての行にクラス名、クラスの時刻と日付、クライアント名、クラスプレゼンターの名前、クライアントの出席状況が表示されます

私は、プレゼンターごとに1つの行を出力する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 >[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

サブクエリはなぜですか? BTW ...エイリアスがありません。 – scsimon

+0

@scsimon:サブクエリを使わずにできるのなら、あなた自身の答えを提示してください。多分、OPが自分の試みで質問に編集していたにもかかわらず... ":-)'。 – halfer

+0

@halferこのクエリは失敗するため、実行されません。期間。構文には複数の問題があります。 – scsimon