1

Gahh..让我沮丧。教科书要求我们在不使用相关子查询的情况下重写以下语句。

SELECT DISTINCT V.VENDOR_NAME, I.INVOICE_NUMBER, I.INVOICE_DATE, I.INVOICE_TOTAL 
FROM VENDORS V
JOIN INVOICES I 
    ON V.VENDOR_ID = I.VENDOR_ID
WHERE I.INVOICE_DATE IN 
    (SELECT MIN(INVOICE_DATE) FROM INVOICES IV WHERE IV.VENDOR_ID = V.VENDOR_ID)
AND I.INVOICE_NUMBER IN 
    (SELECT MIN(INVOICE_NUMBER) FROM INVOICES IV WHERE IV.VENDOR_ID = V.VENDOR_ID)
ORDER BY V.VENDOR_NAME

我怎样才能做到这一点?无论如何我都想不出没有子查询来重写它:S

4

2 回答 2

2

你可以把它写成一个简单LEFT JOIN的,根本没有子查询;

SELECT DISTINCT V.VENDOR_NAME, I.INVOICE_NUMBER, I.INVOICE_DATE, I.INVOICE_TOTAL 
FROM VENDORS V
JOIN INVOICES I 
    ON V.VENDOR_ID = I.VENDOR_ID
LEFT JOIN INVOICES I2
    ON V.VENDOR_ID = I2.VENDOR_ID
   AND (I2.INVOICE_NUMBER < I.INVOICE_NUMBER OR
        I2.INVOICE_DATE   < I.INVOICE_DATE)
WHERE I2.INVOICE_NUMBER IS NULL;

一个用于测试的 SQLfiddle

于 2013-02-20T18:00:16.000 回答
1

试试这个:

SELECT
    DISTINCT V.VENDOR_NAME,
    I.INVOICE_NUMBER,
    I.INVOICE_DATE,
    I.INVOICE_TOTAL 
FROM VENDORS V
    JOIN INVOICES I 
        ON V.VENDOR_ID = I.VENDOR_ID
    JOIN
    (
        SELECT
            VENDOR_ID,
            MIN(INVOICE_DATE) MIN_INVOICE_DATE,
            MIN(INVOICE_NUMBER) MIN_INVOICE_NUMBER
        FROM INVOICES
        GROUP BY VENDOR_ID
    ) MV
    ON V.VENDOR_ID = MV.VENDOR_ID
       AND I.INVOICE_DATE= MV.MIN_INVOICE_DATE
       AND I.INVOICE_NUMBER = MV.MIN_INVOICE_NUMBER
ORDER BY V.VENDOR_NAME
于 2013-02-20T17:50:19.033 回答