我希望我的表中的价格总和取决于其他表中的“ CorpCode”,其中上周之间的Max(InvoiceDate)LastInvoiceDate为“ InvoiceDate”
我的桌子设计是:
T1:
CorpCode AuthorNo
C1 A23
C1 A24
C1 A25
C1 A27
C2 A30
C2 A43
C2 A55
C3 A65
C3 A66
C3 A78
T2:
AuthorNo Price InvoiceDate
A23 145 2019-08-01
A24 132 2019-08-02
A25 140 2019-08-10
A27 125 2019-08-14
A30 115 2019-08-19
A43 110 2019-08-21
A55 100 2019-08-25
A65 111 2019-09-23
A66 133 2019-09-12
A78 54 2019-09-10
Result:
CorpCode SumPrice
C1 265
C2 325
C3 111
答案 0 :(得分:1)
在下面的选项中选中此项-
您可以选中DEMO HERE
SELECT A.CorpCode,SUM(C.Price) SumPrice
FROM
(
SELECT T1.CorpCode, DATEADD(DD,-7,MAX(InvoiceDate)) MX_DATE
-- I have deduct 7 days for a week.
-- But check what you exactly need.
FROM T1 INNER JOIN T2 ON T1.AuthorNo = T2.AuthorNo
GROUP BY T1.CorpCode
)A
INNER JOIN T1 B ON A.CorpCode = B.CorpCode
INNER JOIN T2 C ON B.AuthorNo = C.AuthorNo AND C.InvoiceDate >= A.MX_DATE
GROUP BY A.CorpCode
输出为-
CorpCode SumPrice
C1 265
C2 325
C3 111
答案 1 :(得分:1)
您可以通过多种方式进行操作。即:
with t (CorpCode, Price, days) as
(
select t1.CorpCode, t2.Price,
datediff(d, invoiceDate,
max(InvoiceDate) over (Partition by t1.CorpCode))
from t1
inner join t2 on t1.AuthorNo = t2.AuthorNo
)
select CorpCode, Sum(Price) as TotPrice
from t
where days <= 7
group by CorpCode;