我的表结构:
consumer_id, signup_date, plan_id, subscription_date
它有相同consumer_id的多个subscription_dates。
我希望仅为拥有至少两行数据的用户获取结果 对于每个用户,我需要得到一个结果,它给出了由subscription_date ...
排序的前两行然后我想要拥有至少三行数据的所有用户的另一组结果。 对于每个用户,我需要得到一个结果,它给出了前两行和第三行..
依旧......
我感觉它与this类似,但在我的情况下无法让它起作用..
更新
样本表数据:
1 1/1/2015 1 3/1/2015
2 1/1/2015 1 3/1/2015
2 1/1/2015 1 4/1/2015
3 1/1/2015 1 6/1/2015
2 1/1/2015 1 6/1/2015
3 1/1/2015 1 7/1/2015
示例输出1:
2 1/1/2015 1 3/1/2015
2 1/1/2015 1 4/1/2015
3 1/1/2015 1 6/1/2015
3 1/1/2015 1 7/1/2015
示例输出2:
2 1/1/2015 1 4/1/2015
2 1/1/2015 1 6/1/2015
答案 0 :(得分:0)
这应该可以让你回答你的第一部分,但是为了得到完整的答案,请告诉我们查询的更多细节(如果我们有一些输出会很好) 注意:我假设#test为主表。
select * from
(
SELECT a.consumer_id, a.signup_date, a.plan_id, a.subscription_date
,RANK() OVER
(PARTITION BY a.consumer_id ORDER BY a.subscription_date ASC) AS Rank1
FROM #test a
where a.consumer_id in
(
select consumer_id as count from #test
group by consumer_id
having count(consumer_id)>=2
)
) as b
where b.Rank1<=2
For the second part.
select * from #test
select * from
(
SELECT a.consumer_id, a.signup_date, a.plan_id, a.subscription_date
,RANK() OVER
(PARTITION BY a.consumer_id ORDER BY a.subscription_date ASC) AS Rank1
FROM #test a
where a.consumer_id in
(
select consumer_id as count from #test
group by consumer_id
having count(consumer_id)>=3
)
) as b
where b.Rank1 between 2 and 3