我有一个简单的数据库表,其中列出了customerID和orderDate。我想生成一个网格,显示每个客户在日期范围之间放置了多少订单
e.g。
customerID orderDate
1 2015-01-15
1 2015-01-25
1 2015-02-01
1 2015-04-05
2 2015-02-15
2 2015-02-25
2 2015-03-01
2 2015-03-05
3 2015-02-01
3 2015-05-08
然后我要找的是:
customerID jan2015 feb2015 mar2015 apr2015 may2015
1 2 1 0 1 0
2 0 2 2 0 0
3 0 1 0 0 1
答案 0 :(得分:1)
您可以使用条件聚合。 MySQL有几个有用的date and time functions,您可以将其用于此类查询。在此示例中,我将注意YEAR()
和MONTH()
函数。然后,您可以为每个列编写条件语句,计算每个月和每年中出现的行数,如下所示:
SELECT customer,
SUM(MONTH(orderDate) = 1 AND YEAR(orderDate) = 2015) AS jan2015,
SUM(MONTH(orderDate) = 2 AND YEAR(orderDate) = 2015) AS feb2015,
SUM(MONTH(orderDate) = 3 AND YEAR(orderDate) = 2015) AS mar2015,
SUM(MONTH(orderDate) = 4 AND YEAR(orderDate) = 2015) AS apr2015,
SUM(MONTH(orderDate) = 5 AND YEAR(orderDate) = 2015) AS may2015
FROM orders
GROUP BY customer;
以下是SQL Fiddle示例。