To solve your problem, we need to create a PostgreSQL function that, given a specific date (input_date), returns all rows from the boxofficeday table where the date column matches input_date. For each such row, the function should also include a count of how many prior entries exist for the same movie_id before the input_date.
This can be achieved using a correlated subquery that counts the number of rows for the same movie_id and earlier dates.
✅ Assumptions:
- The
boxofficeday table has at least the following columns: date (of type DATE) and movie_id (of type INT or similar).
- Each row represents a daily box office entry for a specific movie.
- You want to return all columns from
boxofficeday plus a computed prior_count column that counts how many times the same movie_id appeared before the given input_date.
✅ Function Implementation:
CREATE OR REPLACE FUNCTION get_prior_counts(input_date DATE)
RETURNS TABLE (LIKE boxofficeday, prior_count BIGINT) AS
$BODY$
SELECT
b.*,
(SELECT COUNT(*)
FROM boxofficeday b2
WHERE b2.movie_id = b.movie_id
AND b2.date < input_date) AS prior_count
FROM boxofficeday b
WHERE b.date = input_date;
$BODY$
LANGUAGE sql;
✅ Explanation:
✅ Example Usage:
SELECT * FROM get_prior_counts('2023-01-01');
This will return all rows from boxofficeday where the date is '2023-01-01', each with an additional column prior_count indicating how many times that movie appeared in the table before January 1, 2023.
✅ Notes:
- This function assumes that
(movie_id, date) is a unique combination or that duplicates are acceptable and will be handled at the application level.
- If performance becomes an issue, consider adding an index on
(movie_id, date):
CREATE INDEX idx_boxofficeday_movie_date ON boxofficeday (movie_id, date);
✅ Sample Output (Conceptual):
| id | movie_id | date | revenue | prior_count |
|---|
| 123 | 1001 | 2023-01-01 | 100000 | 5 |
| 124 | 1002 | 2023-01-01 | 80000 | 3 |
| 125 | 1003 | 2023-01-01 | 90000 | 2 |
Each row corresponds to a movie's box office data on the given date, along with the number of prior appearances of that movie in the table.
✅ Optional: Return Only Specific Columns
If you only want to return movie_id, date, and prior_count, you can adjust the function like this:
CREATE OR REPLACE FUNCTION get_prior_counts(input_date DATE)
RETURNS TABLE (movie_id INT, date DATE, prior_count BIGINT) AS
$BODY$
SELECT
b.movie_id,
b.date,
(SELECT COUNT(*)
FROM boxofficeday b2
WHERE b2.movie_id = b.movie_id
AND b2.date < input_date)
FROM boxofficeday b
WHERE b.date = input_date;
$BODY$
LANGUAGE sql;
This version is more lightweight and avoids returning unnecessary columns.