Couting combinations within a group

 ̄綄美尐妖づ 提交于 2019-12-24 11:34:27

问题


I need a way way to count combinations of code by patients, so I need to know based on this report total duration of each Service Program Protocol, so based on the picture below I need it to be like this

Patient: 00000036

Adult CSS IND 240

Adult OP IND 120

Patient: 00000040

Adult CSS IND 420

Adult OP IND 60

I am using Microsoft SQL Server 2005 and I would prefer a fix in SQL, but if it could be done in crystal I could work with that. Thank you in advance.

select 

pct.patient_id,
pct.clinic_id,
pct.service_id,
pct.program_id,
pct.protocol_id,
pct.proc_duration


from patient_clin_tran pct
join patient p
on pct.patient_id = p.patient_id and pct.episode_id = p.episode_id
join patient_custom pc
on pct.patient_id = pc.patient_id
join staff s
on pct.attending_id = s.staff_id
where pc.health_home = 'Y'
group by pct.patient_id, pct.clinic_id, pct.service_id, pct.program_id, pct.protocol_id, pct.proc_duration
order by pct.patient_id, pct.clinic_id, pct.service_id, pct.protocol_id


回答1:


You were close. You do need the GROUP BY, but you do not want to GROUP BY the duration column. Instead you want to use the SUM function in the SELECT list on your proc_duration column:

select 
   pct.patient_id,
   pct.clinic_id,
   pct.service_id,
   pct.program_id,
   pct.protocol_id,
   SUM(pct.proc_duration) AS [Total Duration]  

FROM patient_clin_tran pct
  join patient p
  on pct.patient_id = p.patient_id and pct.episode_id = p.episode_id

  join patient_custom pc
  on pct.patient_id = pc.patient_id

  join staff s
  on pct.attending_id = s.staff_id

where pc.health_home = 'Y'
group by pct.patient_id, pct.clinic_id, pct.service_id, pct.program_id, pct.protocol_id
order by pct.patient_id, pct.clinic_id, pct.service_id, pct.program_id, pct.protocol_id


来源:https://stackoverflow.com/questions/22540198/couting-combinations-within-a-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!