-1

I have a table Sales with the following columns -

Emp ID Activity Date Sales
1234 2024-01-01 254.22
1234 2024-05-08 227.10
5678 2023-02-01 254.22
5678 2024-05-01 227.10

I need to find the total trailing 12 months sales of each employee. Not every employee has a sale on each activity date.

The end goal is to answer business questions like - For all employees active in Jan 2024, what was the trailing 12 months sales for them?

Emp ID Activity Date Sales
1234 2024-01-01 254.22
1234 2024-05-08 227.10
5678 2023-02-01 254.22
5678 2024-05-01 227.10

From Sales table, I tried to first do a cross join with a calendar dimension table, but that is not the result I expected. The approach I was thinking was too have all calendar dates, and all employee IDs with sales (0 is no sales for that employee for that date), and then do a partition by empID for rows preceding.

select CAL.*, S.emp_id, S.ACTIVITY_DAte, S.Sales from sales s cross join CAL

1
  • Please provide the proper output that is required. Commented Aug 6, 2024 at 7:08

1 Answer 1

1

Assuming you want the trailing 365 days for each employee and for each activity date of that employee, I would go with a window function:

SELECT 
  s."Emp ID",
  s."Activity Date",
  SUM(s."Sales") OVER (
    PARTITION BY s."Emp ID"
    ORDER BY s."Activity Date"
    RANGE BETWEEN INTERVAL '365 days' PRECEDING AND INTERVAL '1 day' PRECEDING
  ) AS trailing_12mo_sales
FROM sales s

Based on your input, this will give

| Emp ID | Activity Date | Sales  | trailing_12mo_sales |
| ------ | ------------- | ------ | ------------------- |
| 1234   | 2024-01-01    | 254.22 | NULL                |
| 1234   | 2024-05-08    | 227.10 | 254.22              |
| 5678   | 2023-02-01    | 254.22 | NULL                |
| 5678   | 2024-05-01    | 227.10 | NULL                |

At this point, it should be easy to

to answer business questions like - For all employees active in Jan 2024, what was the trailing 12 months sales for them?

by just doing

WITH jan2024_activities AS (
  SELECT *
  FROM (
    SELECT 
      s.*,
      SUM(s."Sales") OVER (
        PARTITION BY s."Emp ID"
        ORDER BY s."Activity Date"
        RANGE BETWEEN INTERVAL '365 days' PRECEDING AND INTERVAL '1 day' PRECEDING
      ) AS trailing_12mo_sales
    FROM sales s
  ) sub
  WHERE DATE_TRUNC('month', "Activity Date") = DATE '2024-01-01'
)
SELECT "Emp ID", MAX(trailing_12mo_sales) AS jan2024_trailing_sales
FROM jan2024_activities
GROUP BY "Emp ID"

--

NOTE: this does not consider leap years. If that was the exact point of your question please clarify and we can slightly tune the queries

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.