Reputation: 35
I do the statistic function for my project. I have the order table with some fields as:
prouct_id
, amount
, order_date
.The customer ask me to do the auto scale statistic as: I get the MIN(order_date)
of a produc_id
and the current date to calculate the days:
If the days about ~ 1 month ==> show the statistic of the product by weeks
If the days about ~ 1 year ==> show the statistic of the product by months
If the days >= 2 year ==> show the statistic of the product by year
I hope that can receive the ideas, examples from all of you about making the statistic as above.
Upvotes: 1
Views: 149
Reputation: 79969
You didn't specify what RDBMS is this. So let me assume that it is SQL Server, and you can do this:
;WITH MinDates AS
(
SELECT
produc_id,
MIN(order_date) order_date
FROM products
GROUP BY produc_id
), DatesWithIntervals AS
(
SELECT
product_id,
order_date,
CASE
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 31 THEN 1
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 THEN 2
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 * 2 THEN 3
ELSE 4
END "Interval"
FROM MinDates
)
SELECT
product_id,
order_date
...
FROM DatesWithIntervals
--Do your statics here
You didn't specify what statistics do you want to compute. But you should be able to do whatever statistics you want to do using the last cte: DatesWithIntervals
depending on the field Interval
and I will leave it as a practice for you.
Edit: For MySQL, just replace all these CTE
s with subqueries like so:
SELECT
product_id,
order_date
...
FROM
(
SELECT
product_id,
order_date,
CASE
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 31 THEN 1
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 THEN 2
WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 * 2 THEN 3
ELSE 4
END "Interval"
FROM
(
SELECT
produc_id,
MIN(order_date) order_date
FROM products
GROUP BY produc_id
) MinDates
) DatesWithIntervals
--Do your statics here
Upvotes: 1