为使用mysql存储过程的用户获取上一个月的付款

为使用mysql存储过程的用户获取上一个月的付款,mysql,stored-procedures,Mysql,Stored Procedures,我有如下的付款记录表 id客户id第n年金额 -- ------- ---- ---- ----- 1 250 1 2 1200 2 300 1,2 2 2400 3 450 12 3 1200 4 450 1 4 1200 5 300 3 2 120

我有如下的付款记录表

id客户id第n年金额
--   -------    ----    ----    -----
1     250        1       2       1200
2     300        1,2     2       2400
3     450        12      3       1200
4     450        1       4       1200
5     300        3       2       1200
6     455        1       3       1200

…etc
您正在
mnth
列中存储CSV月份,这不是最佳的表设计。至少,您应该将每个月存储在单独的一行中,更好的做法是只为每次付款存储一个日期。考虑到当前的设计,以下是一种回答方法:

SELECT
    p1.id,
    p1.cust_id,
    p1.mnth,
    p1.year,
    p1.amount
FROM
(
    SELECT id, cust_id, mnth, year, amount,
        CASE WHEN CONCAT('%,', mnth, ',%') LIKE '%,12,%' THEN 12
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,11,%' THEN 11
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,10,%' THEN 10
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,9,%' THEN 9
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,8,%' THEN 8
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,7,%' THEN 7
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,6,%' THEN 6
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,5,%' THEN 5
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,4,%' THEN 4
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,3,%' THEN 3
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,2,%' THEN 2
             WHEN CONCAT('%,', mnth, ',%') LIKE '%,1,%' THEN 1 END AS mnth_num
    FROM Payment
) p1
INNER JOIN
(
    SELECT
        MAX(CASE WHEN CONCAT('%,', mnth, ',%') LIKE '%,12,%' THEN 12
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,11,%' THEN 11
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,10,%' THEN 10
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,9,%' THEN 9
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,8,%' THEN 8
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,7,%' THEN 7
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,6,%' THEN 6
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,5,%' THEN 5
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,4,%' THEN 4
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,3,%' THEN 3
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,2,%' THEN 2
                 WHEN CONCAT('%,', mnth, ',%') LIKE '%,1,%' THEN 1 END) AS max_mnth,
        MAX(year) AS max_year
    FROM Payment
    WHERE year = (SELECT MAX(year) FROM Payment)
) p2
    ON p1.year = p2.max_year AND
       p1.mnth_num = p2.max_mnth;

首先修复您的设计。请看这里: