问题:我想要返回在生成第一个发票后的前15天内创建的发票总金额
发票表:
ClientID InvoiceDate InvoiceAmt
-------- ----------- ----------
150 1/15/2012 150
150 1/25/2012 1200
150 2/10/2012 800
250 1/12/2012 950
250 1/26/2012 1050
250 2/05/2012 1250
400 1/10/2012 500
400 1/26/2012 700
因此,为每个创建的第一个发票如下:
150 = 1/15/2012
250 = 1/12/2012
400 = 1/10/2012
现在我想计算初始发票日期的15天。所以计算应该返回:
150 = 1/30/2012
250 = 1/27/2012
400 = 1/25/2012
现在我想查询Sumoice InvoiceAmt为适当的日期范围。
150 = 1350
250 = 2000
400 = 500
有什么想法吗?
答案 0 :(得分:2)
您可以使用以下内容(请参阅SQL Fiddle with Demo):
select i1.clientid
, sum(invoiceamt) as Total
from invoice i1
inner join
(
select clientid, min(invoicedate) mindate
from invoice i
group by clientid
) i2
on i1.clientid = i2.clientid
where i1.invoicedate between i2.mindate and dateadd(d, 15, mindate)
group by i1.clientid