我有一种情况,我需要获取FromCountry和ToCountry的组合的最大日期记录的FXRate。
FromCountry ToCountry FXRate FXDate
--------------------------------------------------------
A B 1.14 1/1/2019
A B 1.13 2/1/2019
A B 1.12 3/1/2019
A B 1.11 4/1/2019 -- Expected Record for 'A' and 'B'
c D 1.16 1/1/2019
c D 1.17 2/1/2019
c D 1.18 3/1/2019
c D 1.19 4/1/2019 -- Expected Record for 'C' and 'D'
问题是“ FXView”视图有很多记录,而我目前的方法是这样的
SELECT
fx.FromCountry
, fx.ToCountry
, fx.FXDate
, fx.FXRate
FROM
(
SELECT
FromCountry
, Tocountry
, Max(FXDate) as MaxFXDate
FROM FXView
GROUP BY
FromCountry
, Tocountry
)result
INNER JOIN FXView fx
ON result.FromCountry = fx.FromCountry
AND result.ToCountry = fx.ToCountry
AND result.MaxFXDate = fx.FXDate
我也尝试使用“最大”窗口功能,然后获得它的“独特性”,但这也需要时间。
对于这种性能,是否有更好的解决方案?
注意:此视图中没有任何自然键。
答案 0 :(得分:0)
您可以尝试如下所示的公用表表达式,在某些情况下,它有助于提高性能
WITH result(FromCountry,ToCountry, MaxFXDate) AS(
SELECT
FromCountry
, Tocountry
, Max(FXDate) as MaxFXDate
FROM FXView
GROUP BY
FromCountry
, Tocountry
)
SELECT
fx.FromCountry
, fx.ToCountry
, fx.FXDate
, fx.FXRate
FROM
result
INNER JOIN FXView fx
ON result.FromCountry = fx.FromCountry
AND result.ToCountry = fx.ToCountry
AND result.MaxFXDate = fx.FXDate
答案 1 :(得分:0)
它是否甚至需要分组或加入?
SELECT TOP 1 WITH TIES
fx.FromCountry
, fx.ToCountry
, fx.FXDate
, fx.FXRate
FROM FXView fx
ORDER BY ROW_NUMBER() OVER (PARTITION BY fx.FromCountry, fx.ToCountry ORDER BY fx.FXDate DESC)