如何有条件地将某列的不同值传递给聚合函数?

时间:2012-09-14 08:54:36

标签: sql sql-server tsql

这个问题的标题可能实际上并不能反映出我想要的东西,我想不出更好的东西。也许我应该附加一个'然后加入两个以这种方式获得的表格到最后。

假设我有这张桌子。情况是,我们支付身份loan_id的贷款,我们将付款存储在“付款”表中,每笔付款都有自己的id。当客户付款时,我们会将paid更改为1

+---------+----+--------+------+
| loan_id | id | amount | paid |
+---------+----+--------+------+
|       1 |  1 |   1000 |    1 |
|       1 |  2 |   1000 |    1 |
|       1 |  3 |   1000 |    0 |
|       2 |  4 |  10000 |    0 |
|       3 |  5 |  20000 |    1 |
+---------+----+--------+------+

现在我们需要一份贷款报告。输出应如下所示:

+---------+-------+-----------+
| loan_id |  paid | remaining |
+---------+-------+-----------+
|       1 |  2000 |      1000 |
|       2 |     0 |     10000 |
|       3 | 20000 |         0 |
+---------+-------+-----------+

paid列基本上是所有amount字段的总和,其中pay = 1.而remainingamount行的总和,其中pay = 0。应按loan_id分组。

我尝试了什么:

我尝试了不同的连接,产品等,但我可以从我的查询中获得的最好的事情是:

SELECT loan_id, SUM(paid), SUM(remaining)
FROM (
    SELECT loan_id, 0 AS paid, SUM(amount) AS remaining
    FROM Payment
    WHERE paid = 0
    GROUP BY loan_id

    UNION

    SELECT loan_id, SUM(amount) AS paid, 0 AS remaining
    FROM Payment
    WHERE paid = 1
    GROUP BY loan_id
)
GROUP BY loan_id

但我想应该有比我更好的方法。

2 个答案:

答案 0 :(得分:4)

SELECT 
loan_id, 
SUM(case when paid = 1 then amount else 0 end) as payed, 
SUM(case when paid = 0 then amount else 0 end) as remaining
FROM Payment
GROUP BY loan_id

为避免代码清晰,我会避免使用列名作为别名(付费=>付费)

答案 1 :(得分:2)

这个怎么样:

SELECT Loan_ID,
SUM(Amount*Paid) Paid,
SUM(Amount*(1-Paid)) Remaining
FROM Payment
GROUP BY Loan_ID