MySQL:用过去12个月的总和获取数据

时间:2016-06-17 13:32:33

标签: php mysql

我正在尝试从数据库生成报告,但我遇到查询问题。所以:

我有三张桌子:

  • ordersorder_id, order_date, order_total, clients.client_id, shippings.ship_id
  • clients
  • shippings

现在我希望将fetch orders.*, clients.*, shippings.*作为一行 我可以通过左连接来实现:

SELECT a.*, b.*, c.* 
FROM orders AS a
LEFT JOIN clients AS b ON a.client_id = b.client_id
LEFT JOIN shippings AS c ON a.ship_id = c.ship_id

但是对于那一行,我想要包括12列(即month01,month02,month03),这些列的总和为orders.order_totalorders.order_date指定的过去12个月。

我可以通过获取所有[订单,客户端,发货]行然后通过查询来单独为每一行实现此目的:

SELECT 
    DATE_FORMAT(order_date, \'%m.%Y\') AS order_month,
    SUM(order_total) AS order_sum 
FROM 
    orders
WHERE 
    client_id = '.intval($clientID).'
    AND ship_id = '.intval($shipID).'
    AND order_date >= DATE_SUB(DATE_FORMAT(CURDATE(), \'%Y-%m-01\'), INTERVAL 12 MONTH)
GROUP BY 
    order_month;

但这给了我另外12行数据,其中有两列:order_monthorder_sum

有一种方法可以在一个查询中获取所有这些内容,并在一行中包含几个月吗?

编辑: 样本数据(在这里创建最近4个月):

http://sqlfiddle.com/#!9/139c6

1 个答案:

答案 0 :(得分:1)

我已经写了你的SQL,但我无法测试它。所以我希望它有效。它比你想要的更多一个列(mmonth):从开始的月份

SELECT DATE_FORMAT(order_date, \'%m.%Y\') AS order_month,
  SUM(order_total) AS order_sum,
  @mdiff := (PERIOD_DIFF( DATE(order_date) , DATE(NOW() - INTERVAL 12 MONTH )) / 100),
  SUM(IF(@mdiff =  0 , order_total, 0)) month_01,
  SUM(IF(@mdiff =  1 , order_total, 0)) month_02,
  SUM(IF(@mdiff =  2 , order_total, 0)) month_03,
  SUM(IF(@mdiff =  3 , order_total, 0)) month_04,
  SUM(IF(@mdiff =  4 , order_total, 0)) month_05,
  SUM(IF(@mdiff =  5 , order_total, 0)) month_06,
  SUM(IF(@mdiff =  6 , order_total, 0)) month_07,
  SUM(IF(@mdiff =  7 , order_total, 0)) month_08,
  SUM(IF(@mdiff =  8 , order_total, 0)) month_09,
  SUM(IF(@mdiff =  9 , order_total, 0)) month_10,
  SUM(IF(@mdiff = 10 , order_total, 0)) month_11,
  SUM(IF(@mdiff = 11 , order_total, 0)) month_12
FROM orders
WHERE client_id = '.intval($clientID).'
AND ship_id = '.intval($shipID).'
AND order_date >= DATE_SUB(DATE_FORMAT(CURDATE(), \'%Y-%m-01\'), INTERVAL 12 MONTH)
GROUP BY order_month;

请告诉我是否适合您。