KatInterview

Monthly Line Output Report with Running Totals and Defect Percent

SQL & DataAuto-graded · 15 test cases
MediumAuto-gradedSQL & Datagroup-byhashingrunning-total

Last updated

Group daily production records by line and month, add a per-line running total, and compute each month's defect percentage from summed counts.

Monthly Line Output Report

A factory records one entry per assembly line per production day. Each entry is a list with five values, in this order:

  1. log_id: unique id of the entry (int)
  2. line_id: id of the assembly line (int)
  3. production_date: date string in YYYY-MM-DD format
  4. units_produced: units made that day (int)
  5. units_defective: units from that day flagged as defective (int)

Write a function that turns these daily entries into a monthly report, with one output row for every (line_id, month) pair that appears in the input.

Each output row is a list of five values:

  1. line_id
  2. month: the string YYYY-MM, taken from the date. Different years are different months, so 2023-01 and 2024-01 are separate groups.
  3. total_produced: the sum of units_produced for that line in that month
  4. cumulative_production: the running total of total_produced for that line, adding up its months in chronological order up to and including the current one. The running total restarts for each line.
  5. defect_rate: 100 * (sum of units_defective in the month) / (sum of units_produced in the month), returned as a float and not rounded. It must be computed from the monthly sums, not by averaging daily rates.

Output order

Sort the rows by line_id ascending, then by month ascending. Months with no entries for a line produce no row, and the running total carries over to that line's next month that has data.

Constraints

  • Dates span multiple years.
  • units_produced is greater than 0 in every entry, so the rate never divides by zero.
  • units_defective is a non-negative integer and never exceeds units_produced.
  • Entries may arrive in any order.
  • If the input is empty, return an empty list.

Examples

Example 1

Input: monthly_line_report([[1, 101, '2023-01-05', 100, 5], [2, 101, '2023-01-20', 200, 10], [3, 101, '2023-02-10', 150, 0]])

Output: [[101, '2023-01', 300, 300, 5], [101, '2023-02', 150, 450, 0]]

Hints

Hint 1

Reduce each entry to a key made of the line id and the first 7 characters of the date, and keep two running sums per key: produced and defective.

Hint 2

Sort the keys so each line's months are contiguous and in chronological order. A YYYY-MM string sorts correctly as plain text.

Hint 3

Walk through the sorted keys while keeping a separate cumulative counter per line. Compute the rate from the month's summed counts as defective * 100.0 / produced.