我需要獲取表中可用的最近 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
從這張表中我需要得到最新的 3 月記錄 4 月、3 月和 2 月
示例 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 月的 3 月、1 月、12 月的記錄。
uj5u.com熱心網友回復:
使用DENSE_RANKwithCONVERT僅考慮每條記錄的年月:
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;
uj5u.com熱心網友回復:
首先,我們需要將提到的日期轉換為 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
uj5u.com熱心網友回復:
盡管視窗函式可能看起來很酷,但它們對于這個特定問題可能不會那么有效。
使用子查詢更容易:
SELECT *
FROM yourTable t
WHERE t.date >= (
SELECT DATEADD(month, -3, MAX(tInner.date))
FROM yourTable tInner
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/456571.html
下一篇:無法決議XML
