0

我有一个任务要写一个sql来总结以下数据:

select 
payment,
status, 
interest,
principal
from payment

payment status  interest    principal
1       A       100         0
2       r       0           500
3       o       0           400
4       d       0           100
5       A       0           200
6       A       200         0
7       A       300         0
8       A       0           300
  • 与利息有关的付款将是利息不为 0
  • 与本金有关的付款将是本金不为 0 的情况
  • 数据需要拆分为类型

我正在寻找的结果与此类似:

                 Interest total count           principal total count
Status - A              3                            1
Other                   0                            4
total of all payments   3                            5

我一直在使用分组功能,但无法分组超出利息金额。任何建议将不胜感激。

4

1 回答 1

0

我建议为此使用GROUP BY+ WITH ROLLUP。就像是:

SELECT
    IF(`status` = 'A', 'Status A', 'Others') as `-`,
    SUM(`interest` > 0) as `Interest total count`,
    SUM(`principal` > 0) as `principal total count`
FROM
    (
        SELECT 1 as `payment`, 'A' as `status`, 100 as `interest`, 0 as `principal`
        UNION ALL
        SELECT 2, 'r', 0, 500
        UNION ALL
        SELECT 3, 'o', 0, 400
        UNION ALL
        SELECT 4, 'd', 0, 100
        UNION ALL
        SELECT 5, 'A', 0, 200
        UNION ALL
        SELECT 6, 'A', 200, 0
        UNION ALL
        SELECT 7, 'A', 300, 0
        UNION ALL
        SELECT 8, 'A', 0, 300
    ) as `sub`
GROUP BY 1 WITH ROLLUP;

结果:

-       Interest total count    principal total count
Others          0                       3
Status A        3                       2
                3                       5

询问:

SELECT
    IF(`status` = 'A', 'Status A', 'Others') as `-`,
    SUM(`interest` > 0) as `Interest total count`,
    SUM(`principal` > 0) as `principal total count`
FROM
    `payment`
GROUP BY 1 WITH ROLLUP;
于 2013-10-04T16:19:41.327 回答