1

我有一个查询,我使用 UNION 从两个表中获取数据,它显示正确,但是当我必须选择不同的日期间隔来显示这些日期之间的数据时,问题就来了,发生的情况是它只需要一个 where 子句并应用它在单个 SELECT 部分而不是整个查询上。我需要将其应用于整个...如何?

SELECT
    TICKETS.TICKETID AS TICKET_NO,
    RECEIPTS.DATENEW AS DATENEW,
    PAYMENTS.TOTAL AS MONEY,
    CUSTOMERS.NAME AS CUSTOMER,
    PAYMENTS.PAYMENT AS PAYMENT
FROM RECEIPTS
    LEFT JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
    LEFT JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
    LEFT JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
WHERE ?(QBF_FILTER)
UNION SELECT
    ADJUSTMENTS.TICKET_NO AS TICKET_NO,
    ADJUSTMENTS.DATE AS DATENEW,
    ADJUSTMENTS.ADJUSTMENT_AMOUNT AS MONEY,
    ADJUSTMENTS.CUSTOMER_NAME AS CUSTOMER,
    ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT
FROM ADJUSTMENTS
    LEFT JOIN CUSTOMERS ON CUSTOMERS.ID = ADJUSTMENTS.CUSTOMER_ID
    WHERE ?(QBF_FILTER)

>>>>上面的查询取自 UNICENTA 开源代码项目,它使用 .bs 文件生成报告,当我将 WHERE 子句放在两个选择部分上时,它会生成 SQL 语法错误,现在我上面讨论的问题就是我需要解决的问题解决,谢谢:|

4

1 回答 1

5

您可以使用嵌套的 Select 来完成此操作:

SELECT * FROM (
    SELECT
        TICKETS.TICKETID AS TICKET_NO,
        RECEIPTS.DATENEW AS DATENEW,
        PAYMENTS.TOTAL AS MONEY,
        CUSTOMERS.NAME AS CUSTOMER,
        PAYMENTS.PAYMENT AS PAYMENT
    FROM RECEIPTS
        LEFT JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
        LEFT JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
        LEFT JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
    WHERE ?(QBF_FILTER)
    UNION SELECT
        ADJUSTMENTS.TICKET_NO AS TICKET_NO,
        ADJUSTMENTS.DATE AS DATENEW,
        ADJUSTMENTS.ADJUSTMENT_AMOUNT AS MONEY,
        ADJUSTMENTS.CUSTOMER_NAME AS CUSTOMER,
        ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT
    FROM ADJUSTMENTS
        LEFT JOIN CUSTOMERS ON CUSTOMERS.ID = ADJUSTMENTS.CUSTOMER_ID
        WHERE ?(QBF_FILTER)
    )
WHERE (yourDate between Date1 and Date2)

编辑:我想它需要更像:

SELECT * FROM (
    SELECT
        TICKETS.TICKETID AS TICKET_NO_REC,
        RECEIPTS.DATENEW AS DATENEW_REC,
        PAYMENTS.TOTAL AS MONEY_REC,
        CUSTOMERS.NAME AS CUSTOMER_REC,
        PAYMENTS.PAYMENT AS PAYMENT_REC
    FROM RECEIPTS
        LEFT JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
        LEFT JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
        LEFT JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
    UNION SELECT
        ADJUSTMENTS.TICKET_NO AS TICKET_NO_ADJ,
        ADJUSTMENTS.DATE AS DATENEW_ADJ,
        ADJUSTMENTS.ADJUSTMENT_AMOUNT AS MONEY_ADJ,
        ADJUSTMENTS.CUSTOMER_NAME AS CUSTOMER_ADJ,
        ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT_ADJ
    FROM ADJUSTMENTS
        LEFT JOIN CUSTOMERS ON CUSTOMERS.ID = ADJUSTMENTS.CUSTOMER_ID
    )
WHERE ?(QBF_FILTER)
于 2013-05-29T15:35:18.407 回答