MySQL - 按天计算多个表

时间:2012-12-26 15:39:54

标签: mysql select group-by union

我有各种表来跟踪在系统,销售,客户帐户等中创建的内容,并且他们都创建了时间。我可以使用以下查询每天总结其中任何一个:

select date(created_time), count(*) from customers group by date(created_time)

产生的输出如下:

+--------------------+----------+
| date(created_time) | count(*) |
+--------------------+----------+
| 2012-10-12         |       15 |
| 2012-10-13         |        4 |

虽然没有发生任何事情,但它确实会跳过几天。

然而,我想要做的是同时为多个表生成相同的东西,产生类似的东西:

+--------------------+--------------+------------------+
| date(created_time) | count(sales) | count(customers) |
+--------------------+--------------+------------------+
| 2012-10-12         |           15 |                1 |
| 2012-10-13         |            4 |                3 |

我可以为每个表单独运行查询并手动连接它们,但跳过0天会使连接变得困难。

有没有办法可以在一个mysql查询中执行此操作?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT created_time, SUM(customers), SUM(sales) 
FROM (SELECT DATE(created_time) created_time, COUNT(*) customers, 0 sales 
      FROM customers 
      GROUP BY created_time 
      UNION 
      SELECT DATE(created_time) created_time, 0 customers, COUNT(*) sales 
      FROM sales 
      GROUP BY created_time
     ) as A
GROUP BY created_time;