我正在尝试获取与每个curve_date
值对应的最新tenor_years
相关联的数据,并使用下面的查询执行此操作。但是,我没有得到我想要的数据。
SELECT
tenor_years,
yield_pct,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where fk_yc_update = 12
GROUP BY tenor_years, yield_pct
order by tenor_years
SELECT * FROM yc_node_hist where fk_yc_update = 12
提供以下数据:
id fk_yc_update curve_date tenor_years yield_pct
353443 12 2013-07-26 1 0.1436
353444 12 2013-07-29 1 0.1389
353445 12 2013-07-30 1 0.133
数据如下:
tenor_years yield_pct curve_date
1 0.0828 2014-05-14
1 0.0832 2014-05-19
我希望得到类似的内容:
tenor_years yield_pct curve_date
1 0.0828 2014-05-14
2 0.3232 2015-06-17
..
30
谢谢
答案 0 :(得分:1)
您必须通过以下方式从组中删除yield_pct:
SELECT
tenor_years,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where fk_yc_update = 12
GROUP BY tenor_years;
然后重新加入:
SELECT a.tenor_years, a.curve_date,a.yield_pct
FROM yc_node_hist a
INNER JOIN (
SELECT
tenor_years,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where fk_yc_update = 12) b
ON a.tenor_years=b.tenor_years AND a.curve_date=b.MostRecentDate
ORDER BY tenor_years ASC;
GROUP BY tenor_years;
答案 1 :(得分:1)
SQL Server为此类情况提供PARTITION
/ OVER
功能。
SELECT tenor_years,
yield_pct,
MostRecentDate
FROM (
SELECT
tenor_years,
yield_pct,
curve_date AS "MostRecentDate",
RANK() OVER (PARTITION BY tenor_years ORDER BY curve_date DESC) N
FROM yc_node_hist
where fk_yc_update = 12
)M
WHERE N = 1
ORDER BY tenor_years
这会生成带投影的快速查询,从而无需连接回原始版本。
答案 2 :(得分:0)
with x as
(SELECT
tenor_years,
--yield_pct,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where fk_yc_update = 12
GROUP BY tenor_years --, yield_pct
)
select x.tenor_years, y.yield_pct, y.mostrecentdate
from x join yc_node_hist y on x.mostrecentdate = y.curvedate
CTE是实现它的一种方法,必须删除对yield_pct的分组。
答案 3 :(得分:0)
SELECT tenor_years,
yield_pct,
curve_date
FROM (
SELECT tenor_years,
yield_pct,
curve_date,
MAX(curve_date) OVER (PARTITION BY tenor_years) max_date
FROM yc_node_hist
WHERE fk_yc_update = 12
) [anon]
WHERE curve_date = max_date
ORDER BY tenor_years;