I’m attempting to retrieve a list of customers who have ordered one time in the past three years. I thought that “HAVING COUNT(INVOICE.INVOICE_NO)=1” would get me there, but I’m still getting multiple invoices from the same customers, so I know they’ve ordered more than once. Thanks in advance for the help!
x
SELECT COUNT(INVOICE.INVOICE_NO) AS "Number of Orders",INVOICE.INVOICE_NO, FIRST_ORDER_DT,
LAST_ORDER_DT,(INVOICE.CUSTOMER_ID), ship_first_name, ship_last_name, SHIP_EMAIL
FROM INVOICE, INVOICE_DETAILS, CUSTOMER
WHERE INVOICE.INVOICE_NO = INVOICE_DETAILS.INVOICE_NO
AND CUSTOMER.CUSTOMER_ID = INVOICE.CUSTOMER_ID
AND INVOICE.SHIP_EMAIL IS NOT NULL
AND ORDER_DT BETWEEN '2017-01-01' AND '2019-12-31'
AND (ITEM_NO like 'TD-%'
OR ITEM_NO like 'TB-%'
OR ITEM_NO like 'TVD-%')
GROUP BY INVOICE.CUSTOMER_ID, INVOICE.INVOICE_NO, FIRST_ORDER_DT, LAST_ORDER_DT, ship_first_name,
ship_last_name, SHIP_EMAIL
HAVING COUNT(INVOICE.INVOICE_NO)=1
ORDER BY [LAST_ORDER_DT]DESC
Advertisement
Answer
Your GROUP BY
is causing the problem. Just select information about the individual customer:
SELECT i.CUSTOMER_ID
FROM INVOICE i JOIN
INVOICE_DETAILS id
ON i.INVOICE_NO = id.INVOICE_NO JOIN
CUSTOMER c
ON i.CUSTOMER_ID = c.CUSTOMER_ID
WHERE i.SHIP_EMAIL IS NOT NULL AND
ORDER_DT BETWEEN '2017-01-01' AND '2019-12-31' AND
(ITEM_NO like 'TD-%' OR ITEM_NO like 'TB-%' OR ITEM_NO like 'TVD-%')
GROUP BY i.CUSTOMER_ID
HAVING COUNT(*) = 1;
I also fixed your JOIN
syntax (or lack thereof).