微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL 查询返回每个客户出现多次的付款金额,但不包括单次出现的金额

如何解决SQL 查询返回每个客户出现多次的付款金额,但不包括单次出现的金额

如果我有一个 [客户] 在给定的 [日期] 进行 [付款] 那么如何在不指定客户的情况下逐个查询同一付款值的多次出现?

我想返回这样的东西:

[客户] [付款] [日期]
A 5 1/1
A 5 1/4
B 4 1/2
B 4 1/3
C 9 1/1
C 9 1/5

等等……

解决方法

在 MSSQL Server 中,分区依据非常有用。您可以将列分组并赋予新值。

MSSQL Server partition by

在这种情况下,客户姓名和付款日期必须分组以便可以找到重复值。

客户表和付款表连接代码:

select c.Name,p.PaymentDate,p.PaymentValue from dbo.Customer c inner join dbo.Payment p on c.CustomerId = p.CustomerId order by 1,2 

客户表和付款表示例值:

values

查找重复值的查询:

;WITH CTE AS ( SELECT c.Name,p.PaymentValue,ROW_NUMBER() OVER (PARTITION BY c.Name,p.PaymentValue ORDER BY p.PaymentDate asc) AS [rn] from dbo.Customer c inner join dbo.Payment p on c.CustomerId = p.CustomerId ) select * from cte where rn>1

查询结果:

Duplicate Values

,

如果需要原始数据,请使用 exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.customer = t.customer and
                    t2.payment = t.payment and
                    t2.date <> t.date
             );

如果您只需要客户,则可以使用 group by。这实际上是您可以将 group byselect distinct 一起使用的罕见情况之一:

select distinct customer
from t
group by customer,payment
having min(date) <> max(date);
,

此查询按客户输出重复金额的所有付款。

drop table if exists #temp;
go
create table #temp(
  Customer      nvarchar(50) not null,Payment       int not null,PayDate       date not null);

insert into #temp values
('A',1,'20210101'),('A',5,4,6,('B',('C',9,'20210101');

with pay_cte(Customer,Payment,pay_cnt) as (
    select Customer,count(*)
    from #temp
    group by Customer,Payment
    having count(*)>1)
select *
from #temp t
     join pay_cte p on t.Customer=p.Customer
                       and t.Payment=p.Payment;
Customer    Payment PayDate     Customer    Payment pay_cnt
A           5       2021-01-01  A           5       2
A           5       2021-01-01  A           5       2
B           4       2021-01-01  B           4       2
B           4       2021-01-01  B           4       2
C           9       2021-01-01  C           9       2
C           9       2021-01-01  C           9       2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。