[英]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 |
+----+----------+---------+
如何構造一個查詢,可以給定給定年份的項目總數(按月分組)?
這是一個查詢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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.