如何通过 mysql 中的 id 排除每组中的最后一行?
how to exclude last row in every group by id in mysql?
这 3 列是 employee_id、月份、薪水。如何排除每个 employee_id 组中的最后一行?
[1, 1, 20]
[1, 2, 30]
[1, 3, 40]
[1, 4, 60]
[1, 7, 90]
[1, 8, 90] #exclude
[2, 1, 20]
[2, 2, 30] #exclude
[3, 2, 40]
[3, 3, 60]
[3, 4, 70] #exclude
我的查询添加了行号,但我该怎么办?
select
id, month, salary,
row_number()over(partition by id order by id) as ro #i tried this ,but how?
from employee
order by id, month
您可以在行号中使用 order by month DESC
,然后排除对应于该 ID 最近月份的 1。
select id, month, salary
from (
select
id, month, salary,
row_number()over(partition by id order by month desc) as ro
from employee ) e
where ro > 1
order by id, month;
对于 8.0 之前的版本,可以使用相关子查询来完成此操作。
select * From `table` t where not exists
(select id,max(`month`) mx from `table` group by id having t.id=id and t.`month`=mx)
;
这 3 列是 employee_id、月份、薪水。如何排除每个 employee_id 组中的最后一行?
[1, 1, 20]
[1, 2, 30]
[1, 3, 40]
[1, 4, 60]
[1, 7, 90]
[1, 8, 90] #exclude
[2, 1, 20]
[2, 2, 30] #exclude
[3, 2, 40]
[3, 3, 60]
[3, 4, 70] #exclude
我的查询添加了行号,但我该怎么办?
select
id, month, salary,
row_number()over(partition by id order by id) as ro #i tried this ,but how?
from employee
order by id, month
您可以在行号中使用 order by month DESC
,然后排除对应于该 ID 最近月份的 1。
select id, month, salary
from (
select
id, month, salary,
row_number()over(partition by id order by month desc) as ro
from employee ) e
where ro > 1
order by id, month;
对于 8.0 之前的版本,可以使用相关子查询来完成此操作。
select * From `table` t where not exists
(select id,max(`month`) mx from `table` group by id having t.id=id and t.`month`=mx)
;