Hi, I have an order table, and it has a datetime column called order_date. I want to count the number of orders for each month in 2009. How would I do that?
+5
A:
select month(order_date) as orderMonth, count(*) as orderCount
from order
where year(order_date) = 2009
group by month(order_date)
order by month(order_date)
Jason
2010-01-25 15:57:21
thanks. I was trying what kaleb below suggested,but it refused to recognize orderMonth as a column!
2010-01-25 16:03:06
The use of the functions YEAR() and MONTH() is likely to render any maybe existing index on order_date unusuable. You will run into performance issues once the table grows.
Frank Kalis
2010-01-25 16:07:47
thanks for that comment. however this is a one time deal only. a query that someone requested.
2010-01-25 17:18:42
+1
A:
SELECT MONTH(order_date) AS ordermonth,
COUNT(*) AS ordercount
FROM order
WHERE YEAR(order_date) = 2009
GROUP BY ordermonth;
Kaleb Brasee
2010-01-25 15:57:32
A:
What about using some neat DATETIME trick?
select
DATEADD(MONTH, DATEDIFF(MONTH, 0, order_date), 0) AS orderMonth, count(*) as orderCount
from
[order]
where
order_date >= '2009-01-01'
group by
DATEADD(MONTH, DATEDIFF(MONTH, 0, order_date), 0)
order by
orderMonth
Frank Kalis
2010-01-25 16:12:34