Sql 你知道如何将每个客户最近的发票金额与特定金额进行比较吗?
我们在SQL Server中使用了3个表,一个用于客户事务custrn,一个用于客户详细信息customer,另一个用于保存每个客户必须支付的剩余金额的cusfindata 我需要的是找到最近的发票,但这些发票的总额不得超过他们必须支付的金额 我可以为您提供的其他信息包括:Sql 你知道如何将每个客户最近的发票金额与特定金额进行比较吗?,sql,sql-server,sum,invoice,Sql,Sql Server,Sum,Invoice,我们在SQL Server中使用了3个表,一个用于客户事务custrn,一个用于客户详细信息customer,另一个用于保存每个客户必须支付的剩余金额的cusfindata 我需要的是找到最近的发票,但这些发票的总额不得超过他们必须支付的金额 我可以为您提供的其他信息包括: custtrn.cusid = customer.id and cusfindata.cusid = customer.id 更具体一点,更简单一点:如果我欠一家公司1000欧元,并且我确实有一些公司的发票,我如何才能找到
custtrn.cusid = customer.id
and cusfindata.cusid = customer.id
更具体一点,更简单一点:如果我欠一家公司1000欧元,并且我确实有一些公司的发票,我如何才能找到最近的发票,它们的金额等于或小于1000欧元
数据样本可以是:
在本例中,我需要从Dimitris发票编号16,15,12中检索总计90欧元的发票,因为下一个11号发票的金额超过了100欧元。也许此查询满足您的要求 测试数据:
drop table if exists Customer;
drop table if exists Cusfindata;
drop table if exists Custtrn;
create table Customer (
id int identity,
code int,
name varchar(30)
);
create table Cusfindata (
id int identity,
custid int,
amount numeric(10,0)
);
create table Custtrn (
id int identity,
invoicenumber int,
custid int,
amount numeric(10,0),
invoicedate date
);
insert into Customer(code,name)
values ( 100 , 'Dimitris' ), ( 102 , 'George' ), ( 104 , 'John' );
insert into Cusfindata( custid, amount)
values ( 100, 100 ) , ( 102 , 50 ) , ( 104 , 80 );
insert into Custtrn(invoicenumber,custid,amount,invoicedate)
values ( 1 , 100 , 50 , '20180701' ) , ( 2 , 100 , 30 , '20180708' ) ,
( 3 , 102 , 20 , '20180715' ) , ( 4 , 102 , 56 , '20180722' ) ,
( 5 , 104 , 54 , '20180729' ) , ( 6 , 100 , 80 , '20180805' ) ,
( 7 , 104 , 150 , '20180812' ) , ( 8 , 102 , 20 , '20180819' ) ,
( 9 , 102 , 23 , '20180826' ) , ( 10 , 102 , 60 , '20180902' ) ,
( 11 , 100 , 40 , '20180909' ) , ( 12 , 100 , 20 , '20180916' ) ,
( 13 , 104 , 20 , '20180923' ) , ( 14 , 104 , 30 , '20180930' ) ,
( 15 , 100 , 60 , '20181007' ) , ( 16 , 100 , 10 , '20181014' ) ;
解决方案:
with my_summary as (
select c.code,
c.name,
cf.amount as limit,
ct.invoicedate,
ct.invoicenumber,
ct.amount [invoice amount],
SUM(ct.amount) over (partition by c.code order by ct.invoicedate desc,ct.invoicenumber desc) [total to pay]
from Customer c
join Cusfindata cf on c.code = cf.custid
join Custtrn ct on c.code = ct.custid
-- exclude invoices with amount greater than limit
where ct.amount <= cf.amount
)
select s.*
from my_summary s
where s.[total to pay] <= s.limit;
结果:
这里的大多数人希望样本数据等格式文本,而不是图像或图像链接。A编辑您的标题以总结您的具体技术问题。这里没有人关心你的客户和发票;我们关心一个特殊的技术问题。B你的英语很好,不需要道歉。但你的问题不清楚。为了清晰起见,它可能需要一些重写。我建议您仔细考虑一下。这个问题最好在姐妹网站DBA Stack Exchange上解决。早上好,谢谢您的建议,我会再次提出这个问题。我编辑了Tilt Allready谢谢你,Jacek,我会尝试一下,今天晚些时候回来。今天天气真好!Jacek,我收到一个错误并行数据仓库PDW功能未启用。这是一个版本问题,因为到目前为止我已经看到我的版本是Microsoft SQL Server 2008 SP4-10.0.6000.29 X64 2014年9月3日04:11:34版权c 1988-2008 Microsoft Corporation Standard Edition 64位Windows NT 6.0 Build 6002:Service Pack 2我认为:SUMct.amount over partition by c.code order by ct.invoicedate desc,ct.invoicenumber desc[要支付的总额]与此有关。。。