table 中有重复的记录,我们只需要 select 使用 group by 或 window 函数 sql 中的最新记录
There are duplicate records in table, we need to select only the latest records as per date using group by or window function in sql
在table中有重复的记录,我们需要在sql[=16]中使用group by或window函数只select根据日期的最新记录=]
| emp_id | emp_name | department| create_date
+--------------------------------------------+
| 1 | Nilesh | 10 | 1-JAN-22 |
| 1 | Nilesh | 11 | 5-JAN-22 |
| 2 | Rohit | 12 | 1-JAN-22 |
| 2 | Rohit | 13 | 5-JAN-22 |
代码:
select * from (
select emp_id, emp_name, create_date, department, row_number() over
(partition by date(create_date)
order by create_date desc) as row_num
from emp1)
where row_num = 1
order by create_date;```
您可以像这样简单地使用 GROUP BY
SELECT
emp_id, emp_name, department, MAX(create_date)
FROM
emp1
GROUP BY
emp_id, emp_name, department
如果你想使用 ROW_NUMBER
你必须 PARTITION BY
id
SELECT
emp_id, emp_name, department, create_date
FROM
(
SELECT
emp_id, emp_name, department, create_date, ROW_NUMBER () OVER (partition by emp_id order by create_date desc) as num
FROM
emp1
) sub_query
where num = 1
在table中有重复的记录,我们需要在sql[=16]中使用group by或window函数只select根据日期的最新记录=]
| emp_id | emp_name | department| create_date
+--------------------------------------------+
| 1 | Nilesh | 10 | 1-JAN-22 |
| 1 | Nilesh | 11 | 5-JAN-22 |
| 2 | Rohit | 12 | 1-JAN-22 |
| 2 | Rohit | 13 | 5-JAN-22 |
代码:
select * from (
select emp_id, emp_name, create_date, department, row_number() over
(partition by date(create_date)
order by create_date desc) as row_num
from emp1)
where row_num = 1
order by create_date;```
您可以像这样简单地使用 GROUP BY
SELECT
emp_id, emp_name, department, MAX(create_date)
FROM
emp1
GROUP BY
emp_id, emp_name, department
如果你想使用 ROW_NUMBER
你必须 PARTITION BY
id
SELECT
emp_id, emp_name, department, create_date
FROM
(
SELECT
emp_id, emp_name, department, create_date, ROW_NUMBER () OVER (partition by emp_id order by create_date desc) as num
FROM
emp1
) sub_query
where num = 1