Month-over-month spend change

window functions

Month-over-month spend change

Visa SQL Interview Question

Visa's economics team tracks how card spending moves from one month to the next.

Using approved transactions, find the total spend for each month and how much it changed from the month before. Show the first day of the month as spend_month (a date such as 2024-01-01), the total as total_spend and the change as change_from_previous. The first month has no previous month, so its change_from_previous is NULL. Do not round. Sort the rows by spend_month, earliest first.

Asked of

  • Data Analyst
  • BI Analyst
  • Analytics Engineer
  • Data Engineer
  • Data Scientist

card_transactionsTable18 rows

Column NameType
transaction_idBIGINT
card_idBIGINT
merchant_countryVARCHAR
merchant_categoryVARCHAR
amount_usdDOUBLE
transaction_dateDATE
statusVARCHAR

card_transactionsExample Input

transaction_idcard_idmerchant_countrymerchant_categoryamount_usdtransaction_datestatus
30011United StatesGroceries84.22024-01-04approved
30033CanadaRestaurants52.752024-01-15approved
30056JapanElectronics12992024-01-28approved
30071MexicoTravel2752024-02-08approved
30092United StatesRestaurants68.12024-02-17approved
30116United StatesTravel5202024-02-27declined
30132ItalyTravel780.52024-03-09approved
30153United StatesGroceries120.252024-03-19approved
30174FranceElectronics2202024-03-29approved

Example Output

spend_monthtotal_spendchange_from_previous
2024-01-011435.95NULL
2024-02-01343.1-1092.85
2024-03-011120.75777.65

Explanation

Approved spending was 1,435.95 in January and 343.10 in February, a change of -1,092.85. March's 1,120.75 is 777.65 more than February. January has no earlier month to compare with, so its change is empty. The declined transaction in February is not counted.

The example above is a small slice of the data. Your query runs against the full tables.