我有一个名为a
的表,其他字段为eff_date,policy no
。
现在针对每个策略,考虑所有记录,并从每个月中取出最后更新的记录(eff_date
)。
所以我需要每个政策的每个月的最新更新记录。我该怎么写这个查询?
答案 0 :(得分:2)
我不是百分之百的Teradata语法,但我相信你是在这之后:
SELECT policy_no,eff_date
FROM (SELECT policy_no,eff_date, ROW_NUMBER() OVER (PARTITION BY policy no, EXTRACT(YEAR FROM eff_date),EXTRACT(MONTH FROM eff_date) ORDER BY eff_date DESC) as RowRank
FROM a) as sub
WHERE RowRank = 1
我假设你按月说你也想按年份进行区分,但如果没有,只需从PARTITION BY部分删除EXTRACT(YEAR FROM eff_date)。
编辑:更新Teradata语法。
答案 1 :(得分:1)
SELECT * from a
qualify ROW_NUMBER() OVER (PARTITION BY policy no, EXTRACT(YEAR FROM eff_date),
EXTRACT(MONTH FROM eff_date) ORDER BY eff_date DESC) = 1
答案 2 :(得分:0)
主要的困难是,group by
需要同时是policy_no的组合,还要是月份(从日期中提取)。例如:
在Mysql中
SELECT policy_no,
month(eff_date),
year(eff_date),
max(eff_date)
FROM myTable
GROUP BY policy_no,
month(eff_date),
year(eff_date);
我看到teradata中允许派生表。使用连接到派生表,以下是访问完整行的方法:
select * from a,
(SELECT policy_no,
month(eff_date),
year(eff_date),
max(eff_date) as MaxMonthDate
FROM a
GROUP BY policy_no,
month(eff_date),
year(eff_date)
) as b
where a.policy_no = b.policy_no and
a.eff_date = b.MaxMonthDate;
http://www.sqlfiddle.com/#!2/1f728/5
select * from a,
(SELECT a2.policy_no,
EXTRACT(MONTH FROM a2.eff_date),
EXTRACT(YEAR FROM a2.eff_date),
max(a2.eff_date) as MaxMonthDate
FROM a as a2
GROUP BY a2.policy_no,
EXTRACT(MONTH FROM a2.eff_date),
EXTRACT(YEAR FROM a2.eff_date)
) as b
where a.policy_no = b.policy_no and
a.eff_date = b.MaxMonthDate;
答案 3 :(得分:0)
我将建议查看Windows聚合函数和QUALIFY语句。我相信以下SQL会起作用。
SELECT Policy_No
, EXTRACT(MONTH FROM Eff_Date) AS Eff_Month_
, Eff_Date
FROM TableA
QUALIFY ROW_NUMBER() OVER (PARTITION BY Policy_No, EXTRACT(MONTH FROM Eff_Date)
ORDER BY Eff_Date DESC) = 1;