SQL - 每列的条件

时间:2011-05-23 14:24:44

标签: sql firebird where-clause where firebird2.1

这是一个常见的SQL问题,但我必须知道数据库是Firebird。

我有这张桌子(简化):

user  amount  type
--------------------
john  25      credit
john  20      debit
john  5       debit
john  15      credit
mike  15      credit

我希望使用单个查询得到一个如下所示的结果:

user  credit  debit
--------------------
john  40      25
mike  15      NULL
Where credit = SUM(amount) WHERE type=credit
   and debit = SUM(amount) WHERE type=debit

基本上我希望基于字段的SUM(在这种情况下是数量)在结果上有多个字段,但是在不同的条件下(在这种情况下是类型)。

提前感谢任何建议。

3 个答案:

答案 0 :(得分:6)

标准SQL将是:

SELECT "user",
    SUM(CASE WHEN type='credit' then amount END) as Credit,
    SUM(CASE WHEN type='debit' then amount END) as Debit
FROM
    "table"
GROUP BY
    "user"

答案 1 :(得分:2)

我不确定Firebird是如何做到的,但你可以这样做:

SELECT user, 
sum(SELECT amount FROM table AS t2 WHERE t2.user = t1.user AND type="credit" ) AS credit, 
sum(SELECT amount FROM table AS t3 WHERE t3.user = t1.user AND type="debit" ) AS debit
FROM table AS t1
GROUP BY user
ORDER BY user

我正在引用PostgreSQL中我认为的内容,以防止您找到所需内容。

答案 2 :(得分:0)

试试这个:

SELECT credit.user_name, credit.cre, debit.deb
  FROM (SELECT user_name, SUM(amount) cre FROM t WHERE TYPE = 'credit' GROUP BY user_name) credit
  LEFT OUTER JOIN (SELECT user_name, SUM(amount) deb
                     FROM t
                    WHERE TYPE = 'debit'
                    GROUP BY user_name) debit
    ON (credit.user_name = debit.user_name)