简体   繁体   中英

Mysql PHP - How to calculate individual weighted score for each day record

I have table in mysql database with 4 columns as hashtag_tid,user_id,activity_date and daily_score.

| hashtag_tid | user_id | activity_date | daily_score |
|        1260 |    2488 |    1441823400 |           1 |
|        1280 |    2488 |    1441823400 |           1 |
|        1229 |    5042 |    1441823400 |          23 |
|        1237 |    5042 |    1441823400 |          23 |
|        1260 |    5042 |    1441823400 |          42 |
|        1280 |    5042 |    1441823400 |          67 |
|        1802 |    5042 |    1441823400 |          23 |
|        1852 |    5042 |    1441823400 |          23 |
|        1260 |    2488 |    1441477800 |           1 |
|        1280 |    2488 |    1441477800 |           1 |
|        1229 |    5042 |    1441477800 |          23 |
|        1237 |    5042 |    1441477800 |          23 |
|        1260 |    5042 |    1441477800 |          42 |
|        1280 |    5042 |    1441477800 |          67 |
|        1802 |    5042 |    1441477800 |          23 |
|        1852 |    5042 |    1441477800 |          23 |

In the above table, for the combination of hashtag_tid and user_id I need to apply some weightage to daily_score for each day.

Weightage will be vary for each day like, for today's date daily_score should be daily_score*1, for yesterday daily_score*0.8, It will be different for each day.

Please help me to solve this using MYSQL and PHP.

Thank you

Following can be a possible solution if you will have a constant number of past days to calculate the weighted score.

SELECT `hashtag_tid`, `user_id`, 
  CASE 
    WHEN DATE_FORMAT(FROM_UNIXTIME(`activity_date`), '%Y-%m-%d') = CURDATE() THEN sum(`daily_score`)*1 
    WHEN DATE_FORMAT(FROM_UNIXTIME(`activity_date`), '%Y-%m-%d') = subdate(CURDATE(), 1) THEN sum(`daily_score`)*3 
    ELSE 0 END AS weighted_score 
FROM `tabel` 
Group By `hashtag_tid`, `user_id`, `activity_date`

This is only calculated for last 2 days.

Possible solution if you want to keep the weightings in a table so they can be easily changed in future:-

SELECT hashtag_tid, SUM(h.daily_score + w.weighting)
FROM hashtags h
INNER JOIN weighting w
ON DATEDIFF(CURDATE(), DATE(FROM_UNIXTIME(h.activity_date))) = w.days_diff
GROUP BY hashtag_tid

This is assuming you have a table called weighting with 2 columns, one being the number of days previously and the other being the weighting for that number of days.

Down side is the need to convert the timestamp to a date and then get the date difference on the join is not likely to be fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM