特定值的计数列

时间:2019-01-03 21:43:06

标签: sql

我正在计算以下查询中患者(“全名”)准时赴约的时间百分比。从理论上讲,我可以计算出“按时”值的多少倍,以及“延迟”值的多少倍,按时间设计延迟,并将其乘以100以得到百分比,但是我无法弄清楚该值是多少。将该计算结果显示在列中,然后将患者按其准时得分的百分比分组。

查询示例:

SELECT 

Db.Full_Name,
CASE WHEN (Db.DOCTOR_APPOINTMENT_DATE - Db.ARRIVE_DOCTOR_DATE) + (Db.DOCTOR_APPOINTMENT_TIME - Db.ARRIVE_DOCTOR_TIME) < 0 THEN 'LATE' ELSE 'ON-TIME' END AS STATUS,

FROM Db

WHERE Db.DOCTOR_APPOINTMENT_DATE between to_date('10/30/2018','MM/DD/YYYY') and to_date ('12/30/2018','mm/dd/yyyy')

当前编写的示例输出:

Full_name:       Status:
John Smith       On-Time
John Smith       On-Time
John Smith       Late
John Brown      On-Time
John Brown      On-Time
James White     Late 
John Brown      On-Time
John Brown      Late
James White     Late 
James White     Late 
James White     On-Time

我想要它做什么:

Full_Name:         % on time:
John Brown          75%
James White         25%
John Smith          66%

感谢您的时间!

2 个答案:

答案 0 :(得分:1)

您可以为此使用聚合,尤其是avg()

SELECT Db.Full_Name,
       AVG(CASE WHEN (Db.DOCTOR_APPOINTMENT_DATE - Db.ARRIVE_DOCTOR_DATE) + (Db.DOCTOR_APPOINTMENT_TIME - Db.ARRIVE_DOCTOR_TIME) < 0
                THEN 1.0 ELSE 0.0
           END) as late_ratio
FROM Db
WHERE Db.DOCTOR_APPOINTMENT_DATE BETWEEN DATE '2018-10-30 AND DATE '2018-12-30'
GROUP BY db.Full_Name

答案 1 :(得分:0)

总的Case语句在这里可以很好地工作。您只需要在医生/患者每次按时计数并加总即可。然后,您需要知道所有约会的总和才能获得准确的百分比。我不会使用单行的平均值。

SELECT query with CASE condition and SUM()

     SELECT 

    Db.Full_Name,

    SUM( 
       CASE WHEN (Db.DOCTOR_APPOINTMENT_DATE - Db.ARRIVE_DOCTOR_DATE) +
   (Db.DOCTOR_APPOINTMENT_TIME - Db.ARRIVE_DOCTOR_TIME) < 0 THEN 0 ELSE 1 END

) AS OnTimeCount


--*********************************************
-- insert logic to count the total appointments and divide.**

 , count(somefield) as AppointmentCount

 --******************************
 -- loose example ---

, ( OnTimeCount /  Cast(AppointmentCount as float)) * 100 as OnTimeRatio
FROM Db

WHERE Db.DOCTOR_APPOINTMENT_DATE between to_date('10/30/2018','MM/DD/YYYY') and to_date ('12/30/2018','mm/dd/yyyy')