我正在尝试从医院数据库中计算[访问次数]的总数,以便我可以使用该结果从我的Python脚本中读取并每周将每周摘要发送给我们的团队。因此,我想知道自从我还在学习SQL以来,是否有人可以帮助我进行查询。
Goal Table format:
- Date (prefer dd/mm/yyyy)
- Patient_Name (e.g John)
- Patient_Id (e.g 12345)
- Visits
- Professionals (Categorical Variables: Nurse, Doctor, Assistant Nurse)
因此,我想获得一个查询,该查询可以列出特定日期范围内护士的总访视次数以及一周内特定患者的所有专业人员的总访视百分比。例如,护士拜访患者(John)15次,助理护士拜访10次,而医生薪水每周拜访5次,所以我的最终表是:
____________________________________________
|____Date_____|__Prof__|__Visits_|___Percen__|
|06/01/2018 | Nurse | 15 | 0.5 |
|02/11/2017 | A-Nurse| 10 | 0.33 |
|19/04/2016 | Nurse | 5 | 0.16 |
|
下面是我在SSMS上的SQL语句,我使用了Case语句作为Professionals数据,因为基于患者的需求,有时治疗师会拜访而不是护士/医生,所以我希望这一部分保持动态:
SELECT CONVERT(VARCHAR(10), [myDate], 101), SUM([visits]) AS [Date] , [Professionals], ((SELECT [Visits] from MyHospitalTable)* 100 / (Select SUM([Visits]) From MyHospitalTable)) as Percen
FROM
(SELECT
Count(*) as [total],
[Date] as [myDate],
[Patient_id] as [myPatient_Id],
[Patient_Name] as [myPatient_Name],
[visits] as [visits],
CASE
WHEN [Professionals] LIKE '%Nurse%' THEN 'Nurse'
WHEN [Professionals] LIKE '%Therapist%' THEN 'Therapy'
else 'Unknown'
END AS [Professionals]
FROM [MyHospitalTable]
) a
GROUP BY [myDate]
我了解我的查询不正确,需要改进,如果有人可以帮助我获取数据,那将很棒。
谢谢。
答案 0 :(得分:0)
您可以使用窗口函数计算总计并找到百分比。
下面为您提供了一个方法。但是它与您的表并不完全兼容。
;with ct as (
select MyDate, sum(Visits) Visits
, count(Visits) over (partition by MyDate order by MyDate) TotalVisits
from HospitalTable
group by MyDate
)
select MyDate, Visits, (Visits * 100 / TotalVisits)
from ct