0

我有一个表值函数,它返回一个类似的结果集

id     condition state     costs
1      yes                 300
2      yes                 1000
3      yes                 120
4      no                  20
5      no                  240

该函数本身基于此查询

;with x
as
(
select   c.pat_id
        ,sum(std_cost) as Costs
        from claims as c 
        where c.pat_id in
        (
            select   c.pat_id
                from claims as c
                where c.admission_date between '2007-01-01' and '2007-01-31'
        )
        group by c.pat_id

),y
as
(
    select c.pat_id
        from claims as c
        inner join icd_patient as i
        on i.id=c.id
        inner join tblicd as t
        on t.icd=i.icd
        where t.icd like '707%'
        group by c.pat_id
)               

select   [Condition State]
        ,count(*) as  [Number Patients]
        ,avg(costs) as [Average Healthcare costs]
    from
    (
    select   x.pat_id
            ,case when y.pat_id is null then 'Condition Absent' else 'Condition Present' end as [Condition State]
            ,costs
            from x
            left join y on x.pat_id=y.pat_id
    )r
    group by [Condition State]

该行LIKE '707%'当然由函数中的参数替换。我有一个名为的表tbliICD,其中包含一个代码列表,这是此函数中输入参数的来源。我想知道如何为表中的每个代码运行此查询tblicd。我可以用什么样的方法来做到这一点?是否可以发送包含我需要的每个代码的表值参数并让它为每个代码运行一次函数?

4

1 回答 1

1

使用交叉应用。它看起来像这样:

SELECT
  t.col, t.code, f.id, f.conditionState, f.costs
FROM yourTable AS t
CROSS APPLY dbo.yourTVF(t.code) AS f;

如果您的函数是内联 TVF,这可能非常有效。

于 2013-03-28T01:30:33.050 回答