MySQL的线性方程函数?

时间:2011-04-14 14:21:48

标签: mysql math

我想计算MySQL数据库中某些数据的分数。分数计算如下:

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))

我在带有purchase_time列的表格中进行了删除。

是否可以在MySQL中执行此操作并获得类似于以下内容的输出?

ORDER_ID    SCORE
   3          8
   4          3
   5          15

由于

---编辑--- 表结构是:

tblOrder - table
id - primary key
created - time stamp

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

应该做的伎俩,我目前没有安装mysql所以我无法测试它。

另外,使用datediff查找日期是否在日期范围之间

答案 2 :(得分:0)

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;

答案 3 :(得分:0)

您的年龄与年龄之间需要转换为CASE

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

同时您可以重写表达式,以便特定情况是诸如

之类的因素
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