如何在 SQL Server join 语句中的 where 子句中使用来自左侧 table 的列 在右侧 select 语句中

How to use columns from the left table in where clause in the right select statement in SQL Server join statement

我想将 table 与 select 语句的输出连接起来,我需要在 WHERE 子句中使用表 1 中的列 last_order_date select声明。

例如,看这个截图:

我尝试了以下代码:

SELECT 
    * 
FROM
    Table1 t1
LEFT JOIN 
    (SELECT prod_id, SUM(sales) sales_sum
     FROM Table2
     WHERE transaction_date BETWEEN t1.last_order_date AND CAST(GETDATE()-1 AS DATE)
     GROUP BY prod_id) t2 
ON t1.prod_id = t2.prod_id

显然,问题是我不能在连接语句右侧的 WHERE 子句中使用 t1.last_order_date 。有人可以帮忙吗?

你可以尝试使用OUTER APPLY

SELECT * 
FROM
    Table1 t1
OUTER APPLY 
(
     SELECT t2.prod_id, SUM(t2.sales) sales_sum
     FROM Table2 t2
     WHERE t2.transaction_date BETWEEN t1.last_order_date AND CAST(GETDATE()-1 AS DATE)
     AND  t1.prod_id = t2.prod_id
     GROUP BY t2.prod_id
) t2

根据您的预期结果,我认为您可以像这样使用 LEFT JOIN

SELECT t1.prod_id,
       MIN(t1.last_order_date) last_order_date,
       SUM(ISNULL(t2.sales,0)) sales
FROM
    Table1 t1
LEFT JOIN Table2 t2
ON t2.transaction_date BETWEEN t1.last_order_date 
     AND CAST(GETDATE()-1 AS DATE)
     AND  t1.prod_id = t2.prod_id
GROUP BY t1.prod_id