我有一张这样的桌子:
| date | example_variable |
| 2013-2-22 | cat |
| 2013-3-22 | dog |
| 2013-1-22 | ewe |
| 2013-8-22 | pig |
我已经知道该怎么做是:
SELECT
a.example_variable as V1,
b.example_variable as V2,
c.example_variable as V3,
a.AsOfDate as 1stDate,
b.AsOfDate as 2ndDate,
c.AsOfDate as 3rdDate
FROM <table> a, <table> b, <table> c
WHERE a.AsOfDate = '2013-1-22'
AND b.AsOfDate = '2013-2-22'
AND c.AsOfDate = '2013-3-22'
输出如下:
| V1 | V2 | V3 | 1stDate | 2ndDate | 3rdDate |
| ewe | cat | dog | '2013-1-22' | '2013-2-22' | '2013-3-22' |
在上面的查询中,我手动输入了三个最近的日期。我想要那些自动找到的。似乎我可以使用顶部,但我不确定如何使用。
更复杂的版本:
我已经简化了上面的例子。在我的真实世界案例中,有多个具有相同日期的行,如下所示:
| date | rank | example_variable |
| 2013-2-22 | 1 | cat1 |
| 2013-2-22 | 2 | cat2 |
| 2013-3-22 | 1 | dog1 |
| 2013-3-22 | 2 | dog2 |
| 2013-1-22 | 1 | ewe1 |
| 2013-1-22 | 2 | ewe2 |
| 2013-8-22 | 1 | pig1 |
| 2013-8-22 | 2 | pig2 |
查询是这样的:
SELECT
a.rank, b.rank, c.rank,
a.example_variable as V1,
b.example_variable as V2,
c.example_variable as V3,
a.AsOfDate as 1stDate,
b.AsOfDate as 2ndDate,
c.AsOfDate as 3rdDate
FROM <table> a, <table> b, <table> c
WHERE a.rank = b.rank,
And b.rank = c.rank,
AND a.AsOfDate = '2013-1-22'
AND b.AsOfDate = '2013-2-22'
AND c.AsOfDate = '2013-3-22'
带输出:
| rank | V1 | V2 | V3 | 1stDate | 2ndDate | 3rdDate |
| 1 | ewe1 | cat1 | dog1 | '2013-1-22' | '2013-2-22' | '2013-3-22' |
| 2 | ewe2 | cat2 | dog2 | '2013-1-22' | '2013-2-22' | '2013-3-22' |