Skip to content
Advertisement

What is the most appropriate logic to add rows in table

I have following table structure (simplified to make essential things clear), which lists Top 3 bank customers in each category of loan and branch of the bank. SNO column is rank of the customer, value of which is up to 3.

Loan Category SNO Branch Customer Name Amount
Home Loan 1 abc Piyush 10000
Home Loan 2 abc Shyam 5000
Home Loan 3 abc Kamal 2000
Home Loan 1 xyz Xman 50000
Home Loan 2 xyz Shyam 20000
Auto Loan 1 abc Birendra 10000
Personal Loan 1 xyz Gyan 5000
Personal Loan 2 xyz Prakash 2000

I am trying to make another table such that, If there are less than 3 customers in each loan category and branch, Insert a dummy row for each branch and category with values of customer name and amount as NULL. Essentially, I am trying to get following table.

Loan Category SNO Branch Customer Name Amount
Home Loan 1 abc Piyush 10000
Home Loan 2 abc Shyam 5000
Home Loan 3 abc Kamal 2000
Home Loan 1 xyz Xman 50000
Home Loan 2 xyz Shyam 20000
Home Loan 3 xyz added row
Auto Loan 1 abc Birendra 10000
Auto Loan 2 abc added row
Auto Loan 3 abc added row
Auto Loan 1 xyz added row
Auto Loan 2 xyz added row
Auto Loan 3 xyz added row
Personal Loan 1 xyz Gyan 5000
Personal Loan 2 xyz Prakash 2000
Personal Loan 3 xyz added row
Personal Loan 1 abc added row
Personal Loan 2 abc added row
Personal Loan 3 abc added row

I have solved this problem by using Loop iterating over all category and branch and inserting dummy row, if max(sno) < 3 for each category/branch. But, I am looking for appropriate logic without iterating over all category and branch. In my actual table, there are thousands of branch values and more than 100 categories. So, iterating over all combination of category and branch is very expensive in terms of performance.

I need to write some good logic preferably using SQL constructs only or not using any loop.

Advertisement

Answer

Ok. So you must have some tables where branch and category is listed in single or multiple tables. Lets take it as your branch and category tables and you must have some query which produced the result mentioned in the question. Lets call it your_query.

You need to generate 3 records per branch per category.

Select c.category as loan_category,
       L.lvl as sno, 
       B.branch,
       Q.cutomername,
       Q.amount
  From category c 
  Cross join branch b
  Cross Join (select level lvl from dual connect by level <= 3) l 
  Left Join your_query q on q.branch = c.branch 
                        and q.category = c.category
                        and l.lvl = q.sno
 Ordet by c.category, B.branch, L.lvl
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement