简体   繁体   English

引用父别名时将外部应用转换为左连接

[英]Turning an outer apply into a left join when you reference parent aliases

I'm currently trying to turn an outer apply into a left join to save some complexity.我目前正在尝试将外部应用转换为左连接以节省一些复杂性。

SELECT *
FROM fact_table h
     OUTER APPLY (SELECT TOP 1
                         *
                  FROM dimension mcc WITH (NOLOCK)
                  WHERE h.product = mcc.product
                    AND h.country = mcc.country
                    AND mcc.date IN (SELECT MAX(date)
                                     FROM dimension dd WITH (NOLOCK)
                                     WHERE FORMAT(DATEADD(MONTH, -3, dd.date), 'yyyyMM') <= h.month_in_the_year
                                       AND dd.product = h.product
                                       AND dd.country = h.country)) a;

I basically use it to get the related data from Dimension linked with the latest data point that's earlier than 3 months ago.我基本上使用它从 Dimension 中获取与早于 3 个月前的最新数据点相关联的相关数据。

I'm trying to turn it into a left join, but it's taking a lot more time since I don't filter the dimension before the join:我正在尝试将其变成左连接,但由于我没有在连接前过滤维度,因此需要花费更多时间:

SELECT TOP 10
       *
FROM fact_table h
     LEFT JOIN dimension a ON h.product = a.product
                          AND h.country = a.country
                          AND a.pkid = (SELECT TOP 1
                                               pkid
                                        FROM dimension dd
                                        WHERE FORMAT(DATEADD(MONTH, -3, dd.date), 'yyyyMM') <= h.month_in_the_year
                                        ORDER BY date DESC);

Do you have an idea on how to turn it efficiently into a left join?你知道如何有效地将它变成左连接吗?

It looks like you can significantly simplify this query, by simply adding an ORDER BY .看起来您可以通过简单地添加一个ORDER BY来显着简化此查询。 I've also modified the date filter in order to leverage indexing properly.我还修改了日期过滤器以正确利用索引。

SELECT *
FROM fact_table h
OUTER APPLY (
    SELECT TOP 1 *
    FROM dimension mcc
    WHERE h.product = mcc.product
      AND h.country = mcc.country
      AND mcc.date < DATEADD(MONTH, 2, DATEFROMPARTS(LEFT(h.month_in_the_year, 4), RIGHT(h.month_in_the_year, 2), 1))
    ORDER BY mcc.date DESC
) a;

To transform this into a LEFT JOIN , you need to utilize row-numbering要将其转换为LEFT JOIN ,您需要使用行编号

SELECT *
FROM (
    SELECT *,
      rn = ROW_NUMBER() OVER (PARTITION BY h.PrimaryKeyColumn ORDER BY mcc.date)
    FROM fact_table h
    LEFT JOIN dimension mcc
      ON h.product = mcc.product
        AND h.country = mcc.country
        AND mcc.date < DATEADD(MONTH, 2, DATEFROMPARTS(LEFT(h.month_in_the_year, 4), RIGHT(h.month_in_the_year, 2), 1))
) a
WHERE rn = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM