2

我已经编写 MySQL 查询很长时间了,但是当涉及到这个问题时,我完全觉得自己像个新手,我似乎无法弄清楚如何简化这个查询。基本上我只是想从我们的数据库中生成一个以逗号分隔的收入列表,最终插入谷歌图表。我也必须为“过去的 31 天”做一个,所以我有点搞砸了,除非我想出了如何简化它。

我表中的数据库列是...

  • time:订单进来的时间 int() (UNIX时间戳格式)
  • 价格:十进制的订单是多少(10,2)
SELECT
 CONCAT(
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (6 * 86400)) AND time > (UNIX_TIMESTAMP() - (7 * 86400))),
 ',',
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (5 * 86400)) AND time > (UNIX_TIMESTAMP() - (6 * 86400))),
 ',',
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (4 * 86400)) AND time > (UNIX_TIMESTAMP() - (5 * 86400))),
 ',',
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (3 * 86400)) AND time > (UNIX_TIMESTAMP() - (4 * 86400))),
 ',',
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (2 * 86400)) AND time > (UNIX_TIMESTAMP() - (3 * 86400))),
 ',',
 (SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - 86400) AND time > (UNIX_TIMESTAMP() - (2* 86400)) ),
 ',',
 (SELECT SUM(price) FROM orders WHERE time > (UNIX_TIMESTAMP() - 86400))
 ) as chart_rev 
FROM orders_basic
LIMIT 0,1

如果可能的话,我需要像这样以 24 小时为增量。

与往常一样,非常感谢任何帮助。谢谢!

解决方案

请注意:仔细查看您的结果,它们可能存在,只是顺序错误,如果是,请反转您的排序。

SELECT GROUP_CONCAT(total_sum) AS sum_list FROM
(
    SELECT
        FLOOR((UNIX_TIMESTAMP() - time) / 86400) AS date,
        SUM(price) AS total_sum
    FROM
        orders_basic
    WHERE
        is_testorder < 1
          AND FROM_UNIXTIME(time) > DATE_SUB(NOW(), INTERVAL 1 WEEK)
    GROUP BY
        date
) AS s
4

1 回答 1

3

可能是这样的?

SELECT GROUP_CONCAT(total_sum) AS sum_list FROM
(
    SELECT
        DATE(FROM_UNIXTIME(time)) AS date,
        SUM(price) AS total_sum
    FROM
        orders
    WHERE
        FROM_UNIXTIME(time) > DATE_SUB(NOW(), INTERVAL 1 MONTH)
    GROUP BY
        date
) AS s

这应该为您提供上个月销售总额的逗号分隔列表。但它会按日期分组,而不是 24 小时增量(根据该time列,截止日期将是午夜)。

于 2012-07-12T13:44:15.250 回答