我们说我有一个带有两个简单列的订单表,id和date。
订单
+----+------------+
| id | date |
+----+------------+
| 24 | 2014-04-15 |
| 25 | 2014-07-09 |
| 26 | 2014-09-08 |
| 27 | 2014-09-04 |
| 28 | 2014-04-12 |
+----+------------+
然后我有一个数据透视表,将一堆项目附加到订单。
item_order
+----+----------+---------+
| id | order_id | item_id |
+----+----------+---------+
| 21 | 19 | 20 |
| 22 | 20 | 21 |
| 23 | 21 | 22 |
| 24 | 22 | 23 |
| 25 | 23 | 24 |
+----+----------+---------+
如何构建一个查询,以便为我提供给定年份的总项目数(按月分组)?
答案 0 :(得分:1)
这是join
和group by
查询:
select year(o.date), month(o.date),
count(*) as NumItems, count(distinct oi.item_id) as NumDistinctItems
from orders o join
item_order io
on o.id = io.order_id
group by year(o.date), month(o.date);