Skip to content
Advertisement

Select Distinct in inner join with full customer record

I have two tables one with customer and another with invoices. I need to find all customer that have an more that one invoice with different days with in a period.

Invoice table: Accountnum Datein IStatus …

Customer table: Accountnum …

I have two problems:

1: I can get the customers that have more than one invoice, but I don’t know how to check if they are different days.

2: Customer shows more than one time in this query they need to show only ones.

SELECT c.*
FROM Invoice I
INNER JOIN Customer C
ON I.Accountnum= C.Accountnum
WHERE EXISTS(SELECT DISTINCT I.AccountnumFROM Invoice
         WHERE C.Accountnum = I.Accountnum
         and i.Datein >= '2020-03-01' and i.Datein <= '2020-05-31'
         and (IStatus <> 'V' or IStatus IS NULL)
         GROUP BY I.Accountnum
         HAVING COUNT(*) > 1)

Advertisement

Answer

A simple way to check if a given customer has invoices on two different dates is to ensure that the minimum invoice date differs from the maximum invoice date. You could write this as a join query:

select c.*
from customer c
inner join (
    select accountnum
    from invoice
    where 
        datein >= '2020-03-01' and datein <= '2020-05-31' 
        and (istatus <> 'V' or istatus is null)
    group by accountnum
    having min(datein) <> max(datein)
) i on i.accountnum = c.accountnum
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement