[英]Fetch latest 3 months from records
我需要获取表中可用的最新 3 个月的记录。
示例 1
id name date
1 A 2022-04-05
2 B 2022-04-05
3 A 2022-03-25
4 B 2022-03-24
5 A 2022-02-05
6 B 2022-02-01
7 A 2022-01-01
8 B 2022-01-01
从这张表中,我需要获取 4 月、3 月和 2 月的最新 3 个月记录
示例 2
id name date
1 A 2022-03-05
2 B 2022-03-05
3 A 2022-01-25
4 B 2022-01-24
5 A 2021-12-05
6 B 2021-12-01
7 A 2021-11-01
8 B 2021-11-01
从这张表中,我需要获取 3 月、1 月、12 月的最新 3 个月记录。
将DENSE_RANK
与CONVERT
一起使用以仅考虑每条记录的年月:
WITH cte AS (
SELECT *, DENSE_RANK() OVER (ORDER BY CONVERT(varchar(7), date, 120) DESC) dr
FROM yourTable
)
SELECT id, name, date
FROM cte
WHERE dr <= 3
ORDER BY date DESC;
首先,我们需要将提到的日期转换为 YYYY-MM 格式,以便我们可以从日期列中删除日期。 然后我们需要应用排名逻辑并检索最近 3 个月的数据。 所以最后查询看起来像。
例子:
drop table if exists #temp1;
select 1 as ID ,'A' as Name,'2022-04-05' as date
into #temp1 union all
select 2,'B','2022-04-05' union all
select 3,'A','2022-03-25' union all
select 4,'B','2022-03-24' union all
select 5,'A','2022-02-05' union all
select 6,'B','2022-02-01' union all
select 7,'A','2022-01-01' union all
select 8,'B','2022-01-01'
;WITH FinalOutput AS (
SELECT *, DENSE_RANK() OVER (ORDER BY CONVERT(varchar(7), date, 120) desc) ranks FROM #temp1
)
SELECT id, name, date FROM FinalOutput WHERE ranks <= 3;
drop table if exists #temp;
select 1 as ID ,'A' as Name,'2022-03-05' as date
into #temp union all
select 2,'B','2022-03-05' union all
select 3,'A','2022-01-25' union all
select 4,'B','2022-01-24' union all
select 5,'A','2021-12-05' union all
select 6,'B','2021-12-01' union all
select 7,'A','2021-11-01' union all
select 8,'B','2021-11-01'
;WITH FinalOutput AS (
SELECT *, DENSE_RANK() OVER (ORDER BY CONVERT(varchar(7), date, 120) desc) ranks
FROM #temp
)
SELECT id, name, date FROM FinalOutput WHERE ranks <= 3
尽管 window 函数可能看起来很酷,但对于这个特定问题,它们可能不会那么有效。
使用子查询更容易:
SELECT *
FROM yourTable t
WHERE t.date >= (
SELECT DATEADD(month, -3, MAX(tInner.date))
FROM yourTable tInner
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.