【发布时间】:2015-01-22 13:44:21
【问题描述】:
根据以下SQL 语句,我想合并Matlab 中的两个表,“Returns”和“Yearly”。如何将它们合并到Matlab? (我必须使用 Matlab)
select a.*, b.Equity, b.Date as Yearly_date from Returns a, Yearly b where a.Id = b.Id and a.Date >= b.Date group by a.Id, a.Date having max(b.Date) = b.Date
这是一些示例数据:
Returns = table([repmat(1,5,1);repmat(2,6,1)],[(datetime(2013,10,31):calmonths(1):datetime(2014,2,28)).';(datetime(2013,10,31):calmonths(1):datetime(2014,3,31)).'],randn(11,1),'VariableNames',{'Id','Date','Return'})
Returns =
Id Date Return
__ ___________ ________
1 31-Oct-2013 -0.8095
1 30-Nov-2013 -2.9443
1 31-Dec-2013 1.4384
1 31-Jan-2014 0.32519
1 28-Feb-2014 -0.75493
2 31-Oct-2013 1.3703
2 30-Nov-2013 -1.7115
2 31-Dec-2013 -0.10224
2 31-Jan-2014 -0.24145
2 28-Feb-2014 0.31921
2 31-Mar-2014 0.31286
Yearly = table([repmat(1,3,1);repmat(2,2,1)],[(datetime(2011,12,31):calyears(1):datetime(2013,12,31)).';(datetime(2012,12,31):calyears(1):datetime(2013,12,31)).'],[8;10;11;30;28],'VariableNames',{'Id','Date','Equity'})
Yearly =
Id Date Equity
__ ___________ ______
1 31-Dec-2011 8
1 31-Dec-2012 10
1 31-Dec-2013 11
2 31-Dec-2012 30
2 31-Dec-2013 28
我想要以下输出:
ans =
Id Date Return Equity Yearly_date
__ ___________ __________ ______ ___________
1 31-Oct-2013 -0.86488 10 31-Dec-2012
1 30-Nov-2013 -0.030051 10 31-Dec-2012
1 31-Dec-2013 -0.16488 11 31-Dec-2013
1 31-Jan-2014 0.62771 11 31-Dec-2013
1 28-Feb-2014 1.0933 11 31-Dec-2013
2 31-Oct-2013 1.1093 30 31-Dec-2012
2 30-Nov-2013 -0.86365 30 31-Dec-2012
2 31-Dec-2013 0.077359 28 31-Dec-2013
2 31-Jan-2014 -1.2141 28 31-Dec-2013
2 28-Feb-2014 -1.1135 28 31-Dec-2013
2 31-Mar-2014 -0.0068493 28 31-Dec-2013
【问题讨论】:
-
你能写下预期的输出吗?
-
啊...我会尝试... :)
-
我已经添加了预期的输出
-
对不起,我仍然不清楚,因为 SQL 对我来说看起来并不那么“可读”。所以,如果我能再打扰你,你介意解释一下
Id = 1的预期输出吗? -
当然,对于表 Returns 中的每一行,我想将它与另一个表 Yearly 中具有相同 id 的行合并,并且 Yearly.Date 是最新的日期仍然小于或等于 Returns.Date。因此,对于 Returns 中的 Id = 1 和 Date = '31-Oct-2013',我想将它与 Yearly 中的第 2 行合并,因为 Id 是相同的,并且 '31-Dec-2012' 是最新的 Date 仍然更少大于或等于“2013 年 10 月 31 日”。
标签: matlab merge group-by having