Row_Number Function With PARTITION BY and joining with another table - Oracle SQL

21 Views Asked by At

I have 2 tables 'WithHolding' and 'Eaddress' to represent tax withholdings for employees and storing employee address. Based on work location (and not by their home address), the tax withholding for City is computed. The wihholding information is also stored as Year to Date format.

For the City "CT2", we are trying to determine the 'Total' withholding (by all employees), grouped by their residency status. Example, here is what we are trying to achieve:

Total tax paid by resident employees for CT2: 70 Total tax paid by non-resident employees for CT2: 65 (15+50) Total withholdings for CT2: 135

enter image description here

Tried the below SQL and it seemed to fetch the CT2 withholdings by EmpID:

SELECT *
FROM (
    SELECT EmpID
        ,Withholding_Tilldate AS WITHHOLDING
        ,ROW_NUMBER() OVER (
            PARTITION BY EmpID ORDER BY PayPeriod DESC
            ) AS rn
    FROM WithHolding A 
where A.Locality = 'CT2' AND A.PayPeriod between 202401 and 202403
    ) B
WHERE rn = 1

But couldn't figure out how to join this with Eaddress table to get the SUM based on resident status.

0

There are 0 best solutions below