我有一张会员及其索赔价值表,我有兴趣获得每位会员前3个月的索赔值。这是我到目前为止所尝试的内容:
WITH START as
(SELECT [HEALTH_ID]
,MIN([CLM_MONTH]) as DOS
FROM [TEST]
GROUP BY
[HEALTH_PLAN_ID])
SELECT HEALTH_ID
,DOS
,FORMAT(DATEADD(month, +1, DOS), 'MM/dd/yyyy')
,FORMAT(DATEADD(month, +2, DOS), 'MM/dd/yyyy')
FROM START
我的计划是获取索赔前3个月的日期,然后将索赔金额加入ID和日期。这里的问题不是每个成员都有连续几个月的索赔,而dateadd函数给我连续几个月。例如,如果一个成员在jan,feb,4月,也可能等等声明...我对jan,feb和4月的索赔感兴趣,因为3月份没有索赔。使用dateadd函数会给我日期jan,feb,march不包括四月。
总之,我需要帮助获得具有索赔值的前3个月(月份可能连续或可能不连续)。
答案 0 :(得分:3)
使用dense_rank()
对按Health_Id
分区的月份进行排名,以便过滤每个Health_Id
的前三个月。
;with cte as (
select *
, dr = dense_rank() over (
partition by Health_ID
order by dateadd(month, datediff(month, 0, CLM_Month) , 0) /* truncate to month */
)
from test
)
select *
from cte
where dr < 4 -- dense rank of 1-3
测试数据:
create table test (health_id int, clm_month date)
insert into test values
(1,'20170101'),(1,'20170201'),(1,'20170301'),(1,'20170401')
,(2,'20170101'),(2,'20170201'),(2,'20170401'),(2,'20170501') -- no March
,(3,'20170101'),(3,'20170115'),(3,'20170201'),(3,'20170215') -- Multiple per month
,(3,'20170401'),(3,'20170415'),(3,'20170501'),(3,'20170515')
rextester演示:http://rextester.com/MTZ16877
返回:
+-----------+------------+----+
| health_id | clm_month | dr |
+-----------+------------+----+
| 1 | 2017-01-01 | 1 |
| 1 | 2017-02-01 | 2 |
| 1 | 2017-03-01 | 3 |
| 2 | 2017-01-01 | 1 |
| 2 | 2017-02-01 | 2 |
| 2 | 2017-04-01 | 3 |
| 3 | 2017-01-01 | 1 |
| 3 | 2017-01-15 | 1 |
| 3 | 2017-02-01 | 2 |
| 3 | 2017-02-15 | 2 |
| 3 | 2017-04-01 | 3 |
| 3 | 2017-04-15 | 3 |
+-----------+------------+----+