CREATE TABLE [dbo].[rx](
[pat_id] [int] NOT NULL,
[fill_Date] [date] NOT NULL,
[script_End_Date] AS (dateadd(day,[dayssup],[filldate])),
[drug_Name] [varchar](50) NULL,
[days_Sup] [int] NOT NULL,
[quantity] [float] NOT NULL,
[drug_Class] [char](3) NOT NULL,
CHECK(fill_Date <=script_End_Date
PRIMARY KEY CLUSTERED
(
[clmid] ASC
)
CREATE TABLE [dbo].[Calendar](
[cal_date] [date] NOT NULL,
[julian_seq] [int] IDENTITY(1,1) NOT NULL,
--unsure if the above line is an acceptable way of adding a 'julianized date number', the data in this database ranges from 1-1-2007 to 12-31-2009
PRIMARY KEY CLUSTERED
(
[cal_date] ASC
)
我有我的感興趣的表和上面的結構的日曆表。我試圖在現場drug_class的特定時間(重疊日期)找出一個人在一定數量的家庭中服用的不同藥物的最大數量。按日期範圍進行時間數據分組SQL Server
我在社區的幫助下獲得了類似問題的成功,但此刻我正在做一些不正確的事情,並導致大量不準確的結果。如果可能的話,我想結果集返回到看起來像
create table DesiredResults
(pat_id int, min_overlap date, max_overlap date, drug_class char(3),drug_name varchar(50))
insert into Desired_Results(patid, minoverlap, maxoverlap, drug_class,drug_name)
values (1111,'2008-11-28', '2008-12-18','h3a','drug X')
,(1111,'2008-11-28','2008-12-18','h3a','drug Y')
這將意味着,上述患者111時間幀期間遵醫囑藥物x和藥品Y。
我查詢 -
;with Overlaps (pat_id,cal_date,drug_class)
as
(
select
mdo.pat_id
,c1.cal_date
,mdo.drug_class
from
(
--this gives a table of all the scripts a person had within the classes restricted in the where rx.drug_class IN clause and their fill_date and script_end_dates
SELECT DISTINCT
rx.pat_id
,rx.drug_class
,rx.drug_name
,rx.fill_date
,rx.script_end_date
FROM rx
WHERE rx.drug_class IN('h3a', 'h6h', 'h4b', 'h2f', 'h2s', 'j7c', 'h2e')
--
) as mdo,Calendar as c1
where c1.cal_date between mdo.fill_date and mdo.script_end_date
group by mdo.pat_id,c1.cal_date,mdo.drug_class
having count(*) > 1--overlaps
)
,
Groupings(pat_id,cal_date,drug_class,grp_nbr)
as
(
select
o.pat_id
,o.cal_date
,o.drug_class
,c2.julian_seq
--julianized date
-row_number() over(partition by o.pat_id,o.drug_class order by o.cal_date) as grp_nbr
from Overlaps as o,calendar as c2
where c2.cal_date = o.cal_date
)
,x
as
(
--i think this is what's causing the problem
select pat_id,min(cal_date) as min_overlap,max(cal_date) as max_overlap,drug_class
from groupings
group by pat_id,grp_nbr,drug_class
)
select
x.pat_id
,x.min_overlap
,x.max_overlap
,y.drug_class
,y.drug_name
from x
inner join
(
select distinct
rx.pat_id
,rx.drug_name
,rx.drug_class
,rx.fill_date
from rx
) as y on x.pat_id = y.pat_id and x.drug_class=y.drug_class
and y.fill_date between x.min_overlap and x.max_overlap
order by datediff(day,min_overlap,max_overlap) desc
我找天的跨度,其中大部分藥物在給定的類被規定。不過,現在這給我的日期範圍比任何單個的datediff(day,fill_date,script_end_date)
都大。
這使得數字人爲地膨脹,因爲一些重疊範圍是長達數年,至多它們應該大約是醫生爲劇本編寫劇本的天數。如果在同一天處方'h3a'類中的五種藥物被處方,那麼我將捕獲該時間段爲pat_id
,fill_date
,end_date
, h3a
對於該類中的每種藥物重複5次。