I have a select statement
select distinct month(orderdate) AS [Mon]
, count(orderid) as [Cnt]
from Orders where orderdate >= x and orderdate < y
that returns results like
Mon Cnt
1 1
1 2
2 4
2 3
3 2
4 1
How do I get the results for each month?
Mon Cnt
1 3
2 7
3 2
4 1
2条答案
按热度按时间xpszyzbs1#
You want to count the number of orders by month. You need to group by the month.
so something like this:
bonus::
You can also get this value when you don't use group by with a windowing function -- like this:
ddhy6vgd2#
What I think you're looking for:
You didn't provide any example DDL, or DML, so I used a demo table I already had. The column names are pretty self explanatory and should be easy to map to your own.
All we're doing here is counting the number of rows for each month.
There are some pitfalls to be aware of here. If your date range is ever extended beyond a year, you won't know which year the data belongs to. It's probably a good idea to also include that. You can use
DATEPART(YEAR,InvoiceDateTimeUTC)
to return that. It would also need to be in the group clause.I also want to talk about why DISTINCT didn't do what you expected it to. It returns distinct rows - where each row is different from the others.
Consider:
Now if we apply DISTINCT:
Only a single 1,1 row is returned.
DISTINCT
removed the duplicate, and that's it.