MySQL-基于月份和用户ID的WITH ROLLUP分组

时间:2019-07-05 07:44:35

标签: mysql sql

我想显示的数据库,然后显示该月的总值
例如:

|    ID    |           Name          | Amount |   Date   | Month | Day  | Total |
--------------------------------------------------------------------------------
| ZAK00001 | Committee Meeting April |  4000  | 06-02-19 |   2   |  6   |  4000 |
| Total                                                                 |  4000 |
| ZAK00009 | Meeting May             |  500   | 10-06-19 |   6   |  10  |  1000 | 
| ZAK00011 | Meeting May             |  3000  | 20-06-19 |   2   |  20  |  3000 |
| Total                                                                 |  4000 |

如何在SQL中获得以上数据?到目前为止,我已经尝试使用。

  

更新查询和结果。

我添加IFNULL(a.id, 'Total')

查询

SELECT
    -- a.id,
    IFNULL(a.id, 'Total'),
    m.name,
    a.amount,
    date_format( str_to_date( m.meeting_date, "%d/%m/%Y" ), "%d-%m-%y" ) AS date,
    MONTH (
    str_to_date( m.meeting_date, "%d/%m/%Y" )) AS month,
    DAYOFMONTH(
    str_to_date( m.meeting_date, "%d/%m/%Y" )) AS day,
    sum(a.amount)
FROM
    applications a
    INNER JOIN meeting_application ma ON a.id = ma.application_id
    INNER JOIN meetings m ON ma.meeting_id = m.id 
GROUP BY monthName, a.id WITH ROLLUP

结果

|    ID    |           Name          | Amount |   Date   | Month | Day  | Total |
---------------------------------------------------------------------------------
| ZAK00001 | Committee Meeting April |  4000  | 06-02-19 |   2   |  6   | 4000  |
| Total    | Committee Meeting April |  4000  | 06-02-19 |   2   |  6   | 4000  |
| ZAK00009 | Meeting May             |  1500  | 10-06-19 |   6   |  10  | 1500  |
| ZAK00011 | Meeting May             |  500   | 20-06-19 |   6   |  20  | 500   |
| Total    | Meeting May             |  500   | 20-06-19 |   6   |  20  | 2000  |

我们可以在查询中做到吗?

我能够显示Total文本。如何不显示重复值?

1 个答案:

答案 0 :(得分:1)

应该有一些永久性修复程序,但这也可以解决您的问题: 使用案例声明

SELECT
    -- a.id,
    IFNULL(a.id, 'Total'),
    case when a.id is not null then m.name else null end as name,
    case when a.id is not null then a.amount else null end as amount,
    case when a.id is not null then date_format( str_to_date( m.meeting_date, "%d/%m/%Y" ), "%d-%m-%y" ) else null end AS date,
    case when a.id is not null then MONTH (
    str_to_date( m.meeting_date, "%d/%m/%Y" )) else null end AS month,
    case when a.id is not null then DAYOFMONTH(
    str_to_date( m.meeting_date, "%d/%m/%Y" )) else null end AS day,
    sum(a.amount)
FROM
    applications a
    INNER JOIN meeting_application ma ON a.id = ma.application_id
    INNER JOIN meetings m ON ma.meeting_id = m.id 
GROUP BY monthName, a.id WITH ROLLUP