Counting the number of records per month

I have an order table and it has a datetime column called order_date. I want to calculate the number of orders for each month in 2009. How should I do it?

+3
source share
3 answers
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)

For help, see. month, And yearin Transact-SQL.

+6
source
SELECT MONTH(order_date) AS ordermonth, 
   COUNT(*) AS ordercount 
FROM order 
WHERE YEAR(order_date) = 2009 
GROUP BY ordermonth;
+1
source

How about using a 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
0
source

Source: https://habr.com/ru/post/1729918/


All Articles