select tdd.function_position, date_format(tdd.date,'%Y年%m月')as date, tdd.data from abi_alcc.t_df_data tdd inner join( select function_position,left(date,7),max(date)as max_date from abi_alcc.t_df_data group by function_position,left(date,7) )ib on tdd.function_position=ib.function_position and tdd.date = ib.max_date ; 增加条件如果data为null则返回最近一条不为null的数据
时间: 2024-03-06 09:46:50 浏览: 92
可以通过左连接和子查询实现这个需求,修改后的 SQL 查询语句如下:
```
SELECT tdd.function_position, DATE_FORMAT(tdd.date,'%Y年%m月') AS date, tdd.data
FROM abi_alcc.t_df_data tdd
INNER JOIN (
SELECT function_position, LEFT(date,7), MAX(date) AS max_date
FROM abi_alcc.t_df_data
GROUP BY function_position, LEFT(date,7)
) ib ON tdd.function_position=ib.function_position AND tdd.date = ib.max_date
LEFT JOIN (
SELECT function_position, LEFT(date,7), MAX(date) AS max_date_not_null
FROM abi_alcc.t_df_data
WHERE data IS NOT NULL
GROUP BY function_position, LEFT(date,7)
) ib_not_null ON tdd.function_position=ib_not_null.function_position AND LEFT(tdd.date,7) = LEFT(ib_not_null.date,7)
WHERE tdd.data IS NOT NULL OR (tdd.data IS NULL AND tdd.date = ib_not_null.max_date_not_null)
```
增加了一个左连接子查询,用于找出每个 `function_position` 在每个月份最新的非空数据,然后通过查询条件判断,如果当前数据是空的,则返回该 `function_position` 在该月最新的非空数据。查询结果同样包括 `function_position`、`date`(格式为年月)和 `data` 三个字段。
阅读全文