使用递归的日期范围

时间:2013-01-21 16:22:34

标签: sql sql-server sql-server-2008 tsql recursion

我有一个返回类似于下面的create table查询的结果的查询

create table #testresults
(
  pat_id int,
  fill_date date,
  script_end_date date,
  drug_class char(3),
  distinctDrugs int
)

可以给出pat_id有七种不同类别的药物。 distinctDrugs列是在pat_idfill_date的时间范围内script_end_date可以提供的不同药物的数量。运行查询的结果如下所示: enter image description here

每个pat_id都有许多不同的fill_datescript_end_date时间段。这些不同的时间段每行具有不同的drug_classdistinctDrugs。此示例中的右侧两列表示我需要的内容:我需要每行fill_datescript_end_date每个drug_classdistinctDrugs {{1} }}。我使用此查询将两个最右侧的列添加到我的基本视图

drug_class

对其余的select distinct t.pat_id ,t.fill_date ,t.script_end_date ,t.drug_class ,t.distinctDrugs ,h3a.drug_class as h3aDrugClass ,h3a.distinctDrugs from #temp as t left join ( select pat_id ,fill_date ,script_end_date ,drug_class ,distinctDrugs from #temp where drug_class='h3a' ) as h3a on h3a.pat_id=t.pat_id and h3a.fill_date between t.fill_date and t.script_end_date and t.drug_class !=h3a.drug_class where h3a.drug_class is not null 列执行此操作会很容易,但这不是远程高效的。有没有办法更简单地使用递归(或任何其他方式)?

编辑: 这是我正在寻找的最终产品:

drug_class

这实际上相当快,但绝不是远程的可扩展/可扩展的。以下是结果集的外观: enter image description here

对于每个时间段,您可以查看每种不同药物的drug_class和distinctDrugs的编号。现在,对这个问题有一个更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:0)

在SQL Server中,您使用公用表表达式(CTE)执行递归查询。方法如下:

http://msdn.microsoft.com/en-gb/library/ms186243(v=sql.105).aspx

答案 1 :(得分:0)

因此,递归不是执行此操作的最佳方法。我和

结婚了
select
 pat_id
,fill_date
,script_end_date
,'h3a' as h3a, coalesce(sum(case when drug_class='h3a' then distinctDrugs end),0) as h3aCounts
,'h4b' as h4b, coalesce(sum(case when drug_class='h4b' then distinctDrugs end),0) as h4bCounts
,'h6h' as h6h, coalesce(sum(case when drug_class='h6h' then distinctDrugs end),0) as h6hCounts
,'h2e' as h2e, coalesce(sum(case when drug_class='h2e' then distinctDrugs end),0) as h2eCounts
,'h3a' as h2f, coalesce(sum(case when drug_class='h2f' then distinctDrugs end),0) as h2fCounts
,'h3a' as h2s, coalesce(sum(case when drug_class='h2s' then distinctDrugs end),0) as h2sCounts
,'h3a' as j7c, coalesce(sum(case when drug_class='j7c' then distinctDrugs end),0) as j7cCounts
,row_number() over(order by pat_id) as rn
from x
group by pat_id,fill_date,script_end_date
)