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

廉价感情. 提交于 2019-12-25 18:55:41

问题


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|

回答1:


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;


来源:https://stackoverflow.com/questions/52607775/sql-get-all-payments-where-sum-10-000-in-72-hours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!