从mysql

时间:2015-06-02 11:21:25

标签: php mysql codeigniter

我如何从codeigniter中的(3 months) db获得季度mysql销售趋势?

我有一个数据表

order
-id
-paid_date
-order_total

我希望收到的数据是总订单价值的斜率,而不是过去3个月的订单数量。

型号代码

$results = $this->db->query("SOME_SQL");

我开始写下面但是难以理解如何将结果显示为斜率 ::其中90代表大约3个月

    $day_seconds = 86400;
    $period = 90 * $day_seconds;

    $this->db->select('COUNT(*) AS total', false);
    $this->db->select("FROM_UNIXTIME(`paid_date`, '%Y-%m-%d') AS date", false);
    $this->db->where('paid_date >', time()-$period);

预期输出示例

输出应该只有2个值才能显示趋势。

$results = [ [ 0 => 44 ], [1=>88] ];

理想情况下,需要知道销售总收入是向上还是向下,更高的正斜率表明销售额大幅增加

例如:

//Dramatic Increase of sales
$results = [ [ 0 => 22 ], [1=>150] ];


//Slow Increase of sales
$results = [ [ 0 => 50 ], [1=>55] ];

//Slow Decrease of sales
$results = [ [ 0 => 64 ], [1=>55] ];

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
    *, 
    CASE WHEN last_3 > prev_3 THEN
        'sales up'
    ELSE
        'sales down'
    END AS sales_change,
    (
       CONCAT(((last_3 - prev_3) * 100) / last_3, '%')
    ) AS precentage_change
FROM
    (
        SELECT
            SUM(order_total) AS last_3
        FROM
            TB
        WHERE
            paid_date > UNIX_TIMESTAMP(CURDATE() - INTERVAL 3 MONTH)
    ) AS tb1,
    (
        SELECT
            SUM(order_total) AS prev_3
        FROM
            TB
        WHERE
            paid_date < UNIX_TIMESTAMP(CURDATE() - INTERVAL 3 MONTH)
        AND paid_date > UNIX_TIMESTAMP(CURDATE() - INTERVAL 6 MONTH)
    ) AS tb2

这应该给你4个值:

  • last_3 - 过去3个月的订单总和
  • prev_3 - 此前3个月的订单总和
  • sales_change - 过去3个月销售额增加或减少时的文字
  • precentage_change - 显示过去3个月至3个月之前的百分比销售额变化的数值(含%)

在mySQL中使用INTERVAL,您可以根据需要使用数天或数周进行调整

INTERVAL 1 DAY
INTERVAL 1 WEEK