KatInterview

Calculate Contributor Type Distribution from Activity Logs

SQL & DataModel answer
MediumModel answerSQL & Datadata-cleaningaggregationjoins

Last updated

Clean and aggregate edit logs to compute daily percentages of documents edited by owners versus anonymous users.

Problem

You're building analytics for a collaborative editing platform. Given two datasets containing edit activity and document metadata, compute daily statistics about who is making changes.

Dataset 1: edits.csv Contains every edit made to any document with these fields:

  • user_id: identifier of the editor (may be null for anonymous sessions)
  • doc_id: identifier of the document
  • timestamp: when the edit occurred (ISO 8601 format)
  • edit_size_bytes: size of the change

Dataset 2: documents.csv Contains document metadata:

  • doc_id: identifier of the document
  • owner_id: identifier of the user who created this document
  • created_at: creation timestamp
  • is_private: whether the document is private

Your Task

Produce a summary table showing, for each date, what percentage of actively-edited documents received at least one edit from their owner, and what percentage received at least one edit from an anonymous user.

Return these columns:

  • date: the calendar day
  • percent_owner_edits: percentage of documents edited by their owner that day
  • percent_guest_edits: percentage of documents edited by anonymous users that day

Rules

  • Only count documents where is_private is false
  • An "owner edit" occurs when user_id matches the document's owner_id
  • A "guest edit" occurs when user_id is null
  • Multiple edits to the same document on the same day count as one document
  • A document can contribute to both percentages if it has both types of edits
  • Extract the date from timestamps properly (handle time zones if present)

Example

edits.csv:

user_id,doc_id,timestamp,edit_size_bytes
101,A,2023-01-01T10:00:00,50
,A,2023-01-01T11:00:00,20

documents.csv:

doc_id,owner_id,created_at,is_private
A,101,2023-01-01,false

Expected output:

date,percent_owner_edits,percent_guest_edits
2023-01-01,100.0,100.0

Document A had one edit by its owner (user 101) and one by an anonymous user, so it appears in both numerators. Since it's the only active document that day, both percentages are 100%.

Hints

Hint 1

Think about the unit of measurement: you're counting documents, not individual edits

Hint 2

Use a two-stage aggregation: first collapse to (date, document) pairs, then to dates

Hint 3

A logged-in user who isn't the owner contributes to the denominator but not to either numerator