内部连接到select语句,其中内部select语句的where子句引用外部select?

时间:2012-08-22 16:06:19

标签: sql sql-server sql-server-2008 sql-server-2008-r2

这是对我的更大问题的精简查询,但要点是我正在尝试内部联接到选择受外部选择限制的选择。那可能吗?我在内部选择上收到有关多部分标识符S.Item和S.SerialNum的错误。

要点就是这个,我们必须按项目/序列进行分组,并且查询足够大,我们不希望返回并将整个查询中的所有内容分组为此次要连接。

SELECT S.Item, S.SerialNum, S.ReceiveDate
    FROM SALES S
    INNER JOIN (SELECT W.Item, W.SerialNum, MIN(W.SalesDate)
                    FROM WARRANTY W
                    WHERE W.Item        = S.Item    AND
                          W.SerialNum   = S.SerialNum
                    GROUP BY Item, SerialNum, SalesDate) WW
        ON S.Item = WW.Item AND WW.SerialNum

2 个答案:

答案 0 :(得分:15)

您的JOIN引用似乎错误。

SELECT S.Item, S.SerialNum, S.ReceiveDate
FROM SALES S
INNER JOIN 
(
    SELECT W.Item, W.SerialNum, MIN(W.SalesDate) MinSalesDate
    FROM WARRANTY W
    GROUP BY Item, SerialNum
) WW
        ON S.Item = WW.Item 
       AND S.SerialNum = WW.SerialNum

根据您对过滤的评论进行编辑,您可以在内部WHERE上添加SELECT条款:

SELECT S.Item, S.SerialNum, S.ReceiveDate, WW.MinSalesDate
FROM SALES S
INNER JOIN 
(
    SELECT W.Item, W.SerialNum, MIN(W.SalesDate) MinSalesDate
    FROM WARRANTY W
    WHERE yourFilter here
    GROUP BY Item, SerialNum
) WW
        ON S.Item = WW.Item 
       AND S.SerialNum = WW.SerialNum

答案 1 :(得分:2)

您也可以尝试使用common_table_expression而不是JOIN。 Check the WITH clause here.

可能是这样的:

WITH Warranty_CTE (Item, SerialNum, MinSalesDate)
AS
(
 SELECT W.Item, W.SerialNum, MIN(W.SalesDate) MinSalesDate
    FROM WARRANTY W
    GROUP BY Item, SerialNum
)
SELECT S.Item, S.SerialNum, S.ReceiveDate
FROM SALES S
INNER JOIN Warranty_CTE  WC
        ON S.Item = WC.Item 
       AND S.SerialNum = WC.SerialNum