如何运行TVF X次以满足各种条件

时间:2013-03-28 01:06:25

标签: sql sql-server tsql function

我有一个表值函数,它返回一个像

这样的结果集
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中的每个代码运行此查询。我可以用什么方法来做这件事?是否可以发送包含我需要的每个代码的表值参数,并让它为每个代码运行一次函数?

1 个答案:

答案 0 :(得分:1)

使用CROSS APPLY。它看起来像这样:

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

如果你的功能是内联TVF,这可能非常有效。