给定日期D,是否有办法找出每个用户的当前有效订阅或最近过期的订阅。
这是表结构
user_subscription(
user_subscription_id PRIMARY KEY,
user_id,
subscription_start_date,
subscription_end_date,
user_subscription_count
)
示例数据:
1 1 01-jan-2011 31-jan-2011 1
2 1 01-mar-2011 01-apr-2011 2
3 1 03-jun-2011 05-dec-2011 3
4 2 05-jan-2011 11-jan-2011 1
5 2 01-jun-2011 01-nov-2011 2
示例结果:
D = 15-jan-2011
将是用户1的第1行和用户2的第4行。我正努力想办法在SQL中做到这一点。
目前,我为每个用户单独进行查询,但为数千名用户执行此操作的成本很高。
非常感谢任何帮助/想法!
谢谢!
答案 0 :(得分:1)
您可以使用ROW_NUMBER
:
DECLARE @d DATE = '20110115'
;WITH Cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY subscription_start_date DESC)
FROM user_subscription
WHERE
subscription_end_date <= @d
)
SELECT
user_subscription_id, user_id,subscription_start_date, subscription_end_date
FROM cte
答案 1 :(得分:1)
在这里小提琴:http://sqlfiddle.com/#!3/95688
DECLARE @D AS DATE='15-jan-2011'
;WITH CTE
as
( SELECT *
FROM user_subscription
WHERE (@D BETWEEN subscription_start_date and subscription_end_date) OR subscription_end_date <= @D
),
CTE1
AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY subscription_end_date DESC) AS RN,*
FROM CTE
)
SELECT * FROM CTE1 WHERE RN=1
答案 2 :(得分:1)
假设每个用户的订阅按照user_subscription_count
按时提升,并且只有一个订阅,请尝试:
select *
from user_subscription s
where user_subscription_count =
(select max(x.user_subscription_count)
from user_subscription x
where x.user_id = s.user_id
and x.subscription_start_date < @D)