我目前有一个目前采用这种格式的表格
id | year | jan | feb | mar | apr | may | jun | jul | aug | sep | oct | nov | dec
A 2001 0.00 1.00 0.00 0.00 1.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
A 2003 0.00 1.00 0.00 0.00 1.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
A 2005 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 3.00 0.00 0.00 0.00
我试图得到的结果是这样的
id | firstyear | lastyear | lastpaidamount
A 2001 2005 3.00
我尝试使用此代码,但我得到的最后支付金额为 NULL
SELECT
a.id,
MIN(YEAR) AS firstyear,
MAX(YEAR) AS lastyear,
b.lastpaidadmount
FROM
table1 a
LEFT JOIN
(SELECT
id,
CASE
WHEN dec > 0
THEN dec
WHEN nov > 0
THEN nov
WHEN oct > 0
THEN oct
WHEN sep > 0
THEN sep
WHEN aug > 0
THEN aug
WHEN jul > 0
THEN jul
WHEN jun > 0
THEN jun
WHEN may > 0
THEN may
WHEN apr > 0
THEN apr
WHEN mar > 0
THEN mar
WHEN feb > 0
THEN feb
WHEN jan > 0
THEN jan
END AS lastpaidamount
FROM
table1
WHERE YEAR = 'a.lastyear'
GROUP BY id) b
ON a.id = b.id
WHERE jan > 0
OR feb > 0
OR mar > 0
OR apr > 0
OR may > 0
OR jun > 0
OR jul > 0
OR aug > 0
OR aug > 0
OR sep > 0
OR oct > 0
OR nov > 0
OR dec > 0
GROUP BY id ;
感谢这里的任何帮助,谢谢!