79627937

Date: 2025-05-19 00:09:02
Score: 2.5
Natty:
Report link

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

Reasons:
  • RegEx Blacklisted phrase (2.5): please clarify
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: msabba