简体   繁体   English

SQL中如何获取12个月的连续数据

[英]How to get 12 months continuous data in SQL

I want to get the data for patients who has taken service for 12 months continuously.我想获取连续接受服务 12 个月的患者的数据。 In my data I've Patient_ID and service_date fields.在我的数据中,我有 Patient_ID 和 service_date 字段。

I tried the query below, but the results aren't correct.我尝试了下面的查询,但结果不正确。

select a.*, count(distinct b.svcdate) over(partition by a.patientid, a.svcdate) as events,
count(month(SVCDATE)) over (partition by patientid, SVCDATE) as month_count
from iv_lasix_hf_data_pull as a
left join iv_lasix_hf_data_pull as b
on a.patientid = b.patientid
and b.svcdate >= a.svcdate
and b.svcdate <= dateadd(month, 12, a.svcdate) and month_count = 12;

Thank you for your help!!谢谢您的帮助!!

select a.*, ROW_NUMBER() OVER(ORDER BY month(svcdate) AS ROW_NUMBER, DATEDIFF(M, ROW_NUMBER() OVER(ORDER BY month(svcdate)), svcdate) AS Diff from iv_lasix_hf_data_pull as a left join iv_lasix_hf_data_pull as b on a.patientid = b.patientid and b.svcdate >= a.svcdate and b.svcdate <= dateadd(month, 12, a.svcdate) and month_count = 12; select a.*, ROW_NUMBER() OVER(ORDER BY month(svcdate) AS ROW_NUMBER, DATEDIFF(M, ROW_NUMBER() OVER(ORDER BY month(svcdate)), svcdate) AS Diff from iv_lasix_hf_data_pull 作为左加入 iv_lasix_hf_data_pull 作为 b a.patientid = b.patientid and b.svcdate >= a.svcdate and b.svcdate <= dateadd(month, 12, a.svcdate) and month_count = 12;

The above query will give you the same number in Diff if the months are continuous.如果月份是连续的,上述查询将在 Diff 中为您提供相同的数字。 You can group by and count according to your needs.可以根据需要分组统计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM