如何显示每个客户每个月的最后记录? [英] How to show the last record of each customer for each month?

查看:0
本文介绍了如何显示每个客户每个月的最后记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮帮忙,我有一个表,其中包含过去3年客户记录的更改历史。 并且我需要输出每个客户最后一天的状态或记录。

表格如下:

表A:

| ID  | Name | Number|from_date(in Timestamp)|to_date(in Timestamp)|
|:--- |:----:|:-----:|----------------------:|--------------------:|
|123  | John | 101   |20210101 01:11:15      |20210103 01:11:15    | 
|123  | John | 102   |20210103 01:11:15      |20210301 01:11:15    | 
|123  | John | 103   |20210301 01:11:15      |20210325 01:11:15    | 
|123  | John | 104   |20210325 01:11:15      |20210415 01:11:15    | 
|123  | John | 105   |20210415 01:11:15      |20210416 01:11:15    | 
|123  | John | 106   |20210416 01:11:15      |20210525 01:11:15    |
|123  | John | 104   |20210525 01:11:15      |20210915 01:11:15    | 
|123  | John | 105   |20210915 01:11:15      |null                 |

根据上述数据,遗憾的是,没有2月、6月、7月、8月和9月的记录 但我需要显示每个月(1月至12月)的客户数据。

预期输出应如下所示:

| ID  | Name | Number|Date    |
|123  | John | 102   |20210131|
|123  | John | 102   |20210228|
|123  | John | 104   |20210331|
|123  | John | 106   |20210430|
|123  | John | 104   |20210531|
|123  | John | 104   |20210630|
|123  | John | 104   |20210731|
|123  | John | 104   |20210831|
|123  | John | 104   |20210931|

我可以通过下面的SQL获取from_date列中可见的所有月份的最后一天记录。 但对于未列出的月份或介于from_dateto_date列之间的月份,我很难显示出来。

select a.id, a.name, a.number, last_day(a.from_date) Date
from (select a.*, row_number() over (partition by a.id, trunc(from_date, 'MON') 
order by from_date desc) as seqnum from tableA a
 ) a where seqnum = 1;

供您参考,上面的SQL输出如下:

| ID  | Name | Number|Date    |
|123  | John | 102   |20210131|
|123  | John | 104   |20210331|
|123  | John | 106   |20210430|
|123  | John | 106   |20210531|
|123  | John | 106   |20210931|

Teradata

您可以使用推荐答案的EXPAND ON子句。为此,我们从from_dateto_date创建一个PERIOD数据类型,然后使用EXPAND ON将该时段分为MONTH_END块。

如下所示:

 SELECT yourtable.*, BEGIN(bg) 
 FROM yourtable
 EXPAND ON PERIOD(from_date, NEXT(to_date)) AS by BY ANCHOR MONTH_END;

可能不得不稍微修改一下语法,但这应该会让您大致了解情况。

这篇关于如何显示每个客户每个月的最后记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆