我有一个员工数据库,其中包含有关员工的记录。字段是:
employee_identifier
employee_salary
date_of_the_record
我想为每条记录获取employee_salary
中最后一次更改的日期。哪个SQL查询可以工作?
我尝试了多个子查询,但是它不起作用。
答案 0 :(得分:1)
以下是用于BigQuery标准SQL
#standardSQL
SELECT * EXCEPT(arr),
(SELECT MAX(date_of_the_record) FROM UNNEST(arr)
WHERE employee_salary != t.employee_salary
) AS last_change_in_employee_salary
FROM (
SELECT *, ARRAY_AGG(STRUCT(employee_salary, date_of_the_record)) OVER(win) arr
FROM `project.dataset.employee_database`
WINDOW win AS (PARTITION BY employee_identifier ORDER BY date_of_the_record)
) t
答案 1 :(得分:0)
使用row_number()
with cte as
(
select *,
row_number()over(partition by employee_identifier order by date_of_the_record desc) rn from table_name
) select * from cte where rn=1
答案 2 :(得分:0)
您也可以在没有子查询的情况下执行此操作。如果要所有列:
SELECT as value ARRAY_AGG(t ORDER BY date_of_the_record DESC LIMIT 1)[ordinal(1)]
FROM t t
GROUP BY employee_identifier;
如果只需要日期,请使用GROUP BY
:
SELECT employee_identifier, MAX(date_of_the_record)
FROM t t
GROUP BY employee_identifier;