Ethan Mead Ethan Mead - 1 year ago 63
SQL Question

Count distinct while grouping in MS Access 2010

I have a database of sales and I want to be able to see what has sold during a particular time frame over the years i.e. see what sold most in the last 10 years between July 1 and July 15. Problem is that not all the items were sold every year, and I need to be able to get the average sold. I was able to count distinct years in MySQL but after migrating to Access I can't figure out how to count distinct while still grouping by the individual product.

Relevant fields are StockID (the items' unique id) and TransDate (a datetime that I pull the year from) I've tried things similar to

SELECT Count(*) FROM (SELECT DISTINCT YEAR(Transdate) from Sales)
inside my other query but that always gives me the count from all items (basically giving the number of years in the database) rather than a count for each item.

TL;DR I can either count distinct on the whole DB which is useless or group by StockID without counting distinct which is mildly less useless.

Answer Source

Seems you are looking for select with group by ..

 select  StockID, count(*) 
 from   (select distinct stockID, Year( Transdate) from  my_table )
 group  StockID