我有2个表如下:
表1、用户列表表:
Year Month Id Type
2010 3 1 A
2010 5 2 B
2010 10 1 A
2010 12 1 A
表 2 描述了用户升级历史:
Promote Date Id
2/20/2010 1
5/20/2010 1 (4/2010 the user got demoted, and after 1 month he got promote again)
从这 2 个表中,我需要生成一个与表 1 类似的结果表,但添加一个列,该列对过去 3 个月或特定日期 3 个月以上的 A 类型用户进行分类。例如,结果将是:
Year Month Id | Duration
2010 3 1 | A < 3 months
2010 10 1 | A > 3 months
2010 12 1 | A > 3 months
一般的想法是:
- 我需要将表 1 中的月份列和年份列转换为日期格式,如 3/2010
- 减去与上述日期(2/2010)最接近的促销日期的新转换值,以获得用户被提升的天数
- 比较 90 天来对他的晋升持续时间进行分类
我目前遇到了两个问题。
我不知道将月列和年列转换为月/年日期格式的最佳方法。
假设我已经从 table1 转换了月/年列,我使用 Max 函数从 table2 获取最近的日期。据我所知,max函数对性能不好,那么除了使用max之外,还有其他解决方案吗?在mysql中,使用Limit 1很容易解决,但是SAS proc-sql不支持Limit。proc-sql中是否有任何等效的限制?以下是我目前正在考虑的代码。
PROC SQL;
Create table Result as SELECT table1.Year, table1.Month, table1.Code,
(Case When table1.Type = "B" then "B"
When table1.Type = "A" AND (table1.Date - (Select MAX(table2.Date) From table2 Where table2.Date <= table1.Date AND table2.Id = table1.Id ) < 90) THEN "A < 3 months"
When table1.Type = "A" AND (table1.Date - (Select MAX(table2.Date) From table2 Where table2.Date <= table1.Date AND table2.Id = table1.Id ) >= 90) THEN "A > 3 months"
When table1.Type = "C" then "C"
end) as NewType
From table1
LEFT JOIN
// ....
;
QUIT;
如您所见,我需要将 table1 与其他表左连接,因此我使用子查询,这也是一个糟糕的性能,但我不知道是否有其他方法。帮助和建议表示赞赏。