[英]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 ...发票表:Accountnum Datein IStatus ...
Customer table: Accountnum ...客户表: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. 1:我可以拿到不止一张发票的客户,但是我不知道如何查看他们是不是不同的日子。
2: Customer shows more than one time in this query they need to show only ones. 2:客户在此查询中显示不止一次,他们只需要显示一次。
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)
You are close, but no JOIN
in the outer query:您很接近,但在外部查询中没有JOIN
:
SELECT c.*
FROM Customer C
WHERE (SELECT COUNT(*)
FROM 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)
) > 1;
Note that I also changed the logic of the subquery.请注意,我还更改了子查询的逻辑。 The subquery returns a count which is then compared to 1
, rather than using EXISTS
.子查询返回一个计数,然后将其与1
进行比较,而不是使用EXISTS
。
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:你可以把它写成一个join
查询:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.