I want to compute scores for some data I have in a MySQL database. The score will be computed as follows:
score = COUNT(purchases MADE BETWEEN NOW() AND (NOW() - 1 WEEK))
+ 0.7 * COUNT(purchases MADE BETWEEN (NOW() - 1 WEEK) AND (NOW() - 2 WEEKS))
+ 0.4 * COUNT(purchases OLDER THAN (NOW() - 2 WEEKS))
I have purchses in a table with a purchase_time column.
Is it possible to do this in MySQL and get output similar to the following?
ORDER_ID SCORE
3 8
4开发者_如何学Python 3
5 15
Thanks
--- EDIT --- The table structure is:
tblOrder - table
id - primary key
created - time stamp
SELECT orderId,
SUM
(
CASE
WHEN purchase_date > NOW() - INTERVAL 1 WEEK AND purchase_date <= NOW() THEN
1
WHEN purchase_date > NOW() - INTERVAL 2 WEEK AND purchase_date <= NOW() - INTERVAL 1 WEEK THEN
0.7
ELSE
0.3
END
)
FROM mytable
GROUP BY
orderId
Your between and older need to be converted into CASE.
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
At the same time you can rewrite the expression so that specific cases are the factors such as
SELECT SUM(
CASE DATEDIFF(now(),purchase_datetime) DIV 7
WHEN 0 THEN 1
WHEN 1 THEN 0.7
ELSE 0.4
END
)
FROM table
WHERE purchase_datetime < now()
GROUP BY ORDER_ID
SELECT ORDER ID, COUNT(purchases MADE BETWEEN NOW() AND (NOW() - 1 WEEK))
+ 0.7 * COUNT(purchases MADE BETWEEN (NOW() - 1 WEEK) AND (NOW() - 2 WEEKS))
+ 0.4 * COUNT(purchases OLDER THAN (NOW() - 2 WEEKS)) AS SCORE
FROM TABLE
should do the trick, I don't currently have mysql installed so I can't test it.
also, use datediff to find if a date is between the range of dates
SELECT order_id, sum(score) FROM
(
(SELECT Order_id, COUNT(id) AS Score FROM purchases
WHERE purchase_time BETWEEN CURDATE() AND DATE_SUB(CURDATE(),INTERVAL 1 WEEK))
GROUP BY order_id
UNION ALL
(SELECT Order_id, (COUNT(id) * 0.7) AS score FROM purchases
WHERE purchase_time BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 WEEK)
AND DATE_SUB(CURDATE(),INTERVAL 2 WEEK))
GROUP BY order_id
UNION ALL
(SELECT Order_id, (COUNT(id) * 0.4) AS score FROM purchases
WHERE purchase_time < DATE_SUB(CURDATE(),INTERVAL 2 WEEK))
GROUP BY order_id
) s
GROUP BY order_id;
精彩评论