简体   繁体   中英

SQL Group By Month From Date Column On Different Table

Let's say I have an orders table with two simple columns, id and date.

orders

+----+------------+
| id | date       |
+----+------------+
| 24 | 2014-04-15 |
| 25 | 2014-07-09 |
| 26 | 2014-09-08 |
| 27 | 2014-09-04 |
| 28 | 2014-04-12 |
+----+------------+

I then have a pivot table attaching a bunch of items to orders .

item_order

+----+----------+---------+
| id | order_id | item_id |
+----+----------+---------+
| 21 |       19 |      20 |
| 22 |       20 |      21 |
| 23 |       21 |      22 |
| 24 |       22 |      23 |
| 25 |       23 |      24 |
+----+----------+---------+

How can I construct a query that will give me a count of total items (group by month) for a given year?

This is a join and group by query:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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