• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Postgres update table using CTE with priority

Resolved: Postgres update table using CTE with priority

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a employee leave balance table as follows
emp_code leave_type yearmonth Balance Priority
1 PL 202205 2 0
1 SL 202205 1 1
2 PL 202205 3 0
2 SL 202205 1 1
3 PL 202205 1 0
3 SL 202205 1 1

and a Attendance Table as follows
emp_code date yearmonth Attendance Leave
3 2022-05-01 202205 1
3 2022-05-02 202205 1
3 2022-05-03 202205 1
1 2022-05-01 202205 0
1 2022-05-02 202205 0
1 2022-05-03 202205 0
1 2022-05-04 202205 0
2 2022-05-01 202205 1
2 2022-05-02 202205 1

I just wanted to update the attendance table with the respective leave (based on the priority and availability) if the attendance field value is 0
For eg: employee 1 have 3 leave balance and 4 days absent
After the update, the records for emp_code 1 in attendance should be as follows
emp_code date yearmonth Attendance Leave
1 2022-05-01 202205 0 PL
1 2022-05-02 202205 0 PL
1 2022-05-03 202205 0 SL
1 2022-05-04 202205 0

I know, we can do this through SP or function. But my company policy does not allow me to create SP or functions (I can update this via my backend code, but there are millions of records there to be updated so I am worried about the performance)
I wonder, is there any ways to achieve this in PG using CTE/Window function/any other means ?
here is a fiddle https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/4952
Thanks

Answer:

If the last attendance record in your fiddle is in error and removed, then my approach would be:
  1. Expand the leave balance for the month into rows using generate_series() and assign row numbers based on the priority
  2. Assign row numbers to absences within a month
  3. Calculate changes by left join from absences to leave records

Your updated fiddle

If you have better answer, please add a comment about this, thank you!

postgresql
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: how to get and read an xml file in a zip file using xml.etree

02/04/2023

Resolved: The ‘Access-Control-Allow-Origin’ header contains multiple values ‘*, *’, but only one is allowed. cors error not resolving

02/04/2023

Resolved: SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘crm.email’ doesn’t exist (Connection: mysql, SQL: select count(*) as aggregate from `email`

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.