SQL Server Total count for each month; but month gives duplicate entries; even with distinct keyword

2wnc66cl  于 2023-06-28  发布在  其他
关注(0)|答案(2)|浏览(119)

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
xpszyzbs

xpszyzbs1#

You want to count the number of orders by month. You need to group by the month.

so something like this:

select month(orderdate) as mon,  count(distinct orderid) as order_count
from Orders
where orderdate >= x and orderdate < y
group by month(orderdate)

bonus::

You can also get this value when you don't use group by with a windowing function -- like this:

select -- whatever
       count(orderid) over (partition by month(orderdate)) as order_count
 from orders
ddhy6vgd

ddhy6vgd2#

What I think you're looking for:

SELECT DATEPART(MONTH,InvoiceDateTimeUTC), COUNT(InvoiceID)
  FROM Invoices
 WHERE InvoiceDateTimeUTC >= '2023-01-01' 
   AND InvoiceDateTimeUTC < '2023-04-30 23:59:59.997'
 GROUP BY DATEPART(MONTH,InvoiceDateTimeUTC)
MonthCount
34323
14161
44144
23848

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:

DECLARE @Table TABLE (Month INT, Count INT);
INSERT INTO @Table (Month, Count) VALUES (1,1),(2,1),(1,1),(1,2);

SELECT *
  FROM @Table
MonthCount
11
21
11
12

Now if we apply DISTINCT:

SELECT DISTINCT *
  FROM @Table
MonthCount
11
12
21

Only a single 1,1 row is returned. DISTINCT removed the duplicate, and that's it.

相关问题