I have a table that stores salary information (SALARY with fields such as NATIONAL_ID, SALYEAR, SALMONTH, SALAMOUNT, DATE_PAID, etc) for employees.
I need to extract data from that table including the last month an employee was paid a salary.
Unfortunately, DATE_PAID column is null for many cases in that table which forces me to think of using a combination of SALYEAR, SALMONTH to determine the highest value.
SALMONTH stores numbers from 1-12 and SALYEAR stores year information ie 2010, 2015, etc.
Using ROW_NUMBER
, we can try:
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY NATIONAL_ID
ORDER BY SALYEAR DESC, SALMONTH DESC) rn
FROM yourTable t
)
SELECT *
FROM cte
WHERE rn = 1;
The above approach will target the latest record for each NATIONAL_ID
, with "latest" being defined as having the most recent month in the most recent year.
select max(to_date(sal_year||to_char(sal_month,'FM00'),'yyyymm'))
should do it. The TO_DATE is really just for completeness if you want a date datatype.
You would need to use COALESCE
like this:
SELECT MAX(COALESCE(YEAR(DATE_PAID) * 100 + MONTH(DATE_PAID), SALYEAR * 100 + SALMONTH))
FROM tablename
Use Correlated Sub Query -
with temp as (
select national_id,
max(to_number(to_char(salyear)||lpad(to_char(salmonth),2,'0'))) as max_salmonthyear
from salary
group by national_id)
select *
from salary s, temp t
where s.national_id = t.national_id
and to_number(to_char(salyear)||lpad(to_char(salmonth),2,'0')) = t.max_salmonthyear
order by 1;
Why not just use aggregation?
select nationalid, max(salyear * 100 + salmonth) as salyearmonth
from t
group by nationalid;
If you want to convert the yearmonth to a date:
select nationalid,
to_date(max(salyear * 100 + salmonth), 'YYYYMM') as salyearmonth
from t
group by nationalid;
This returns the first date of the salary month.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.