SQL Query用于获取大于或小于10k的多个付款之间的总和

时间:2017-06-28 23:49:56

标签: sql sql-server-2014

我正在尝试编写一个查询,以便从帐户中获得一个月的付款总额。我已经能够获得它,但我已经遇到了障碍。我的挑战是,我需要计算付款金额<&lt; 10000或=&gt; 10000.业务规则是单笔付款不得超过10000,但可以进行多次付款,总金额可以超过10000.作为一个简单的模拟数据库,它可能看起来像

ID | AccountNo | Payment
1  | 1         | 5000
2  | 1         | 6000
3  | 2         | 5000
4  | 3         | 9000
5  | 3         | 5000

所以我期望的结果会像

NumberOfPaymentsBelow10K | NumberOfPayments10K+
1                        | 2

我想避免执行函数或存储过程,并且更喜欢子查询。

非常感谢您对此查询的任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用SUM和GROUP BY ...

获取每个帐户的总计
SELECT AccountNo, SUM(Payment) AS TotPay
FROM payments
GROUP BY AccountNo

您可以使用该结果来计算超过10000的数字

SELECT COUNT(*)
FROM (
    SELECT AccountNo, SUM(Payment) AS TotPay
    FROM payments
    GROUP BY AccountNo
)
WHERE TotPay>10000

如果您愿意,可以在单个查询中获取数字和数字,但这更复杂:

SELECT
   COUNT(CASE WHEN TotPay<=10000 THEN 1 END) AS Below10K,
   COUNT(CASE WHEN TotPay> 10000 THEN 1 END) AS Above10K
FROM (
    SELECT AccountNo, SUM(Payment) AS TotPay
    FROM payments
    GROUP BY AccountNo
)

答案 1 :(得分:1)

我建议尽可能避免使用子查询,因为它会影响性能,特别是如果您有大量数据,那么,您可以使用类似Common Table Expression的内容。您可以使用以下方法执行相同的操作:

;WITH CTE
AS
(
    SELECT AccountNo, SUM(Payment) AS TotalPayment
    FROM Payments
    GROUP BY AccountNo
)

SELECT
    SUM(CASE WHEN TotalPayment < 10000 THEN 1 ELSE 0 END) AS 'NumberOfPaymentsBelow10K',
    SUM(CASE WHEN TotalPayment >= 10000 THEN 1 ELSE 0 END) AS 'NumberOfPayments10K+'
FROM CTE