On this page

SQL: Solving Histogram of Tweets

3 min
  • SQL
  • PostgreSQL

A short SQL walkthrough for Histogram of Tweets.

The problem is from DataLemur — Histogram of Tweets.

Problem

Using the tweets table, count how many users posted one tweet, two tweets, and so on during 2022. Return tweet_bucket (tweet count) and users_num (user count).

Table structure

Column nameType
tweet_idinteger
user_idinteger
msgstring
tweet_datetimestamp

Example input

Times are omitted for readability:

tweet_iduser_idmsgtweet_date
214252111Am considering taking Tesla private at $420. Funding secured.2021-12-30
739252111Despite the constant negative press covfefe2022-01-01
846402111Following @NickSinghTech on Twitter changed my life!2022-02-14
241425254If the salary is so competitive why won’t you tell me what it is?2022-03-01
231574148I no longer have a manager. I can't be managed2022-03-23

Example output

tweet_bucketusers_num
12
21

Users 254 and 148 each posted one tweet in 2022, while user 111 posted two. The tweet from December 2021 is excluded.

Approach

My first thought was: before I can count users with the same number of tweets, I need to know how many tweets each user posted. So I filter the data to 2022, then use GROUP BY user_id with COUNT(tweet_id). This becomes the inner query: one row per user, with their tweet count stored as bucket.

Now I can treat that result as a new table. If two users each posted one tweet, they each have a row with bucket = 1. In the outer query, I group by bucket and use COUNT(user_id) to count those users. The two queries answer two questions in order: how many tweets did each user post, then how many users share that count?

Query

SELECT
    bucket AS tweet_bucket,
    COUNT(user_id) AS users_num
FROM (
    SELECT
        user_id,
        COUNT(tweet_id) AS bucket
    FROM tweets
    WHERE tweet_date >= '2022-01-01'
      AND tweet_date < '2023-01-01'
    GROUP BY user_id
) AS total_tweets
GROUP BY bucket;

I submitted this solution on DataLemur and received a Solved verdict.

The upper bound < '2023-01-01' includes all of December 31, 2022.