从一组数据中的多个字段创建摘要报告

时间:2013-10-04 16:12:19

标签: mysql

我有一个编写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

我一直在使用群组功能,但未能超出兴趣金额。任何建议将不胜感激。

1 个答案:

答案 0 :(得分: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;