繁体   English   中英

SQL从不同表上的日期列按月分组

[英]SQL Group By Month From Date Column On Different Table

假设我有一个包含两个简单列的订单表,即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 |
+----+----------+---------+

如何构造一个查询,可以给定给定年份的项目总数(按月分组)?

这是一个查询joingroup 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM