我的表名为tnx_line_transfer。架构如下
现在我想生成如下所示的输出
输出
我正在尝试下面的查询,但它没有显示正确的输出。这个查询有什么问题
SELECT
main_tbl.operator_id,
main_tbl.production_line
FROM
tnx_line_transfer main_tbl
INNER JOIN (
SELECT
operator_id,
max(date) AS max_date
FROM
tnx_line_transfer
GROUP BY
operator_id
) temp ON main_tbl.operator_id = temp.operator_id
如果有其他替代方案,请告诉我。谢谢。
答案 0 :(得分:3)
您错过了与date
加入max_date
列。
SELECT main_tbl.operator_id,
main_tbl.production_line
FROM tnx_line_transfer main_tbl
INNER JOIN (SELECT operator_id,
Max(`date`) AS max_date
FROM tnx_line_transfer
GROUP BY operator_id) temp
ON main_tbl.operator_id = temp.operator_id
AND main_tbl.max_date = temp.`date` --here
另一种方法是使用Sub-Query
SELECT main_tbl.operator_id,
main_tbl.production_line
FROM tnx_line_transfer main_tbl
WHERE `date` = (SELECT Max(`date`)
FROM tnx_line_transfer temp
WHERE main_tbl.operator_id = temp.operator_id)
Row_Number
概念在上述方案中派上用场但不幸的是Mysql
不支持Window function's