gpt4 book ai didi

mysql - 使用 mysql 存储过程获取用户的最后付款月份

转载 作者:行者123 更新时间:2023-11-29 09:32:28 25 4
gpt4 key购买 nike

我有如下所示的付款条目表

id   cust_id    mnth    year    amount
-- ------- ---- ---- -----
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

从另一个表获取月份和年份像下面这样。

id     mnth

1 January

2 February

...etc

id   year 

1 2016

2 2017

3 2018

...etc

我想从第一个表中获取最后付款的月份和年份。如何做到这一点

最佳答案

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

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;

Demo

关于mysql - 使用 mysql 存储过程获取用户的最后付款月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com