0

我有一个 SQL 查询,我必须从两个不同的表(比如 a1、a2)中获取值。出于简单的原因,它可以工作,但是由于一个重要原因(从表 a2 中获取一个值以放置在 a1 的列值之间),我在同一个查询中有一个 UNION,因此我的查询结果很奇怪。这是我的查询和图像,显示了相同 TICKET_ID 的重复条目,我想删除它,如何?

询问

SELECT 
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
 RIGHT JOIN ADJUSTMENTS ON ADJUSTMENTS.CUSTOMER_ID = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC

这是它的输出图像

输出

在此处输入图像描述

4

2 回答 2

1

您可以使用 GROUP BY 或只检查原因列不为空

SELECT q.* FROM (

SELECT 
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
 RIGHT JOIN ADJUSTMENTS ON ADJUSTMENTS.CUSTOMER_ID = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC ) q GROUP BY q.TICKETID

或者

 ORDER BY NAME ASC, DATE DESC ) q GROUP BY q.REASON !='' // q.REASON IS NOT NULL
于 2013-07-24T18:39:16.137 回答
0

最后我想通了,现在查询如下

SELECT
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 (SELECT ADJUSTMENTS.ADJUSTMENT_REASON FROM ADJUSTMENTS WHERE ADJUSTMENTS.ADJUSTMENT_TYPE != 'adjustment' AND ADJUSTMENTS.ADJUSTMENT_REASON != '') AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC
于 2013-07-25T05:30:03.477 回答