MySQL简化了这个查询?

时间:2012-07-12 13:28:11

标签: mysql database reporting google-visualization simplify

我一直在编写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

1 个答案:

答案 0 :(得分: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列。)