Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Pivot Rows Into Columns

HardSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Pivot Rows Into Columns. Start with the requirements and the three tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

The dv01 Performance Data surface receives monthly loan-level servicing records for securitization deals. Write a PostgreSQL query that produces one portfolio summary row per deal as of January 31, 2025.

Requirements

  1. Retain every deal, including deals with no active loans or no performance record as of the reporting date.
  2. Use only the latest performance record for each active loan on or before January 31, 2025. Resolve duplicate records by choosing the greatest loaded_at value.
  3. Pivot loan balances into current_balance, dpd_30_balance, dpd_60_balance, and dpd_90_plus_balance columns based on delinquency_days.
  4. Calculate total_balance and the percentage of total balance that is 90 or more days delinquent.
  5. Return results ordered by deal_id.

Representative Sample Data

dv01_deals contains deals D001 through D008. Active loans include loans 101 and 102 in D001, 103 and 104 in D002, and one active loan each in D003 through D006. D007 has only a paid-off loan, while D008 has no loans.

Schema

dv01_deals
ColumnTypeDescription
deal_idPKVARCHAR(10)Unique securitization deal identifier
deal_nameVARCHAR(100)Display name for the deal
asset_classVARCHAR(50)Underlying asset category
loan_tape
ColumnTypeDescription
loan_idPKINTUnique loan identifier
deal_idVARCHAR(10)Deal containing the loan
loan_statusVARCHAR(20)Loan lifecycle status
loan_performance
ColumnTypeDescription
loan_idINTLoan associated with the performance record
reporting_monthDATEMonth represented by the record
loaded_atTIMESTAMPTimestamp when the record was loaded
delinquency_daysINTDays the loan is past due
principal_balanceNUMERIC(14,2)Principal balance at the reporting date
Tablesdv01_dealsloan_tapeloan_performance
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results