Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

sql server - SQL get all Payments where sum > 10,000 in 72 hours

i'm working on a fictional payment database, and i want to check if there are payments from a merchant which sum of it goes above 10k within 72 hours from each other.

SELECT o.MerchantID, SUM(Amount) FROM Payments p 
INNER JOIN Orders o ON p.OrderID = o.ID
WHERE MerchantCreatedOrderOn BETWEEN MerchantCreatedOrderOn AND DATEADD(HOUR, 72, MerchantCreatedOrderOn)
GROUP BY o.MerchantID, o.MerchantCreatedOrderOn, p.ID
HAVING SUM(o.Amount) >= 10000;

now my where clause isn't right yet, i now get only payments where the sum is above 10k but not when it's in 72 hours..

my desired result: all the payments id's from payments which sum > 10,000 in 72 hours.

this is on SQL-server 14.0.100

i only need the payment id's from those who exceed 10k in 72 hours so:

|ID    |
|427683|
|427685|
|427688|
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From my comment, I assume you want to check every orders from 72 hours from date order. The formula actually -72 hours from date order

SELECT o.MerchantID, SUM(Amount) FROM Payments p 
INNER JOIN Orders o ON p.OrderID = o.ID
WHERE MerchantCreatedOrderOn BETWEEN MerchantCreatedOrderOn AND DATEADD(HOUR, -72, MerchantCreatedOrderOn)
GROUP BY o.MerchantID, o.MerchantCreatedOrderOn, p.ID
HAVING SUM(o.Amount) >= 10000;

I just changing 72 become -72.

But if I get you correctly, actually you want 72 hours by now, which like this?

SELECT o.MerchantID, SUM(Amount) FROM Payments p 
INNER JOIN Orders o ON p.OrderID = o.ID
WHERE MerchantCreatedOrderOn >= DATEADD(HOUR, -72, getdate())
GROUP BY o.MerchantID, o.MerchantCreatedOrderOn, p.ID
HAVING SUM(o.Amount) >= 10000;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...