mysql通过订单创建时间按年统计各市1到12月份的订单量,优化版本
时间: 2023-01-11 18:55:36 浏览: 84
订单统计表
你可以这样写 SQL 语句:
```
SELECT city,
SUM(CASE WHEN month = 1 THEN num_orders ELSE 0 END) AS 'Jan',
SUM(CASE WHEN month = 2 THEN num_orders ELSE 0 END) AS 'Feb',
SUM(CASE WHEN month = 3 THEN num_orders ELSE 0 END) AS 'Mar',
SUM(CASE WHEN month = 4 THEN num_orders ELSE 0 END) AS 'Apr',
SUM(CASE WHEN month = 5 THEN num_orders ELSE 0 END) AS 'May',
SUM(CASE WHEN month = 6 THEN num_orders ELSE 0 END) AS 'Jun',
SUM(CASE WHEN month = 7 THEN num_orders ELSE 0 END) AS 'Jul',
SUM(CASE WHEN month = 8 THEN num_orders ELSE 0 END) AS 'Aug',
SUM(CASE WHEN month = 9 THEN num_orders ELSE 0 END) AS 'Sep',
SUM(CASE WHEN month = 10 THEN num_orders ELSE 0 END) AS 'Oct',
SUM(CASE WHEN month = 11 THEN num_orders ELSE 0 END) AS 'Nov',
SUM(CASE WHEN month = 12 THEN num_orders ELSE 0 END) AS 'Dec'
FROM orders
WHERE year = ? -- 这里的 ? 是占位符,查询时需要替换成真实的年份
GROUP BY city;
```
假设表 `orders` 中有如下几列:
- `id`:订单 ID,数字型。
- `city`:订单所在市,字符型。
- `year`:订单创建的年份,数字型。
- `month`:订单创建的月份,数字型。
- `num_orders`:订单数量,数字型。
这条 SQL 语句会按市分组,统计出每个市在每个月的订单数量。
希望这个答案对你有所帮助!
阅读全文