Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have SQL Table with articles with dates inside, and I want to check how many days in month are with records?

For example: In January 2019 I have only 15 days with records the rest not and then in February 2019 I have a few other but not full February, so how can see the total number of days with records on each month of the year.

What I have tried:

  select day(Date) as 'Day', count(*) as 'number of days',
	   CONVERT(char(7), date, 120) As [year]
from [dbo].[Expenses]
where Day(date) is not null
group by day(Date),CONVERT(char(7), date, 120) 


This is something that I tried but I don't get the right numbers.
Thankfully
Posted
Updated 18-Jul-20 23:51pm
Comments
Richard MacCutchan 19-Jul-20 4:36am    
The logical answer is to select all records for a specific month and then count the number of unique days in the set. And why would you have records with the day value as null?
Member 13410460 19-Jul-20 8:07am    
Hi, Thank you for your answer, I need to count only the days that I have bought something.

1 solution

Try this:

SQL
SELECT DATENAME(MONTH, MONTH([Date])) AS ForMonth
       ,COUNT(*) AS NumberOfDays
       ,YEAR([Date]) AS ForYear
FROM   [dbo].[Expenses]
where  [Date] IS NOT NULL
GROUP BY YEAR([Date]), MONTH([Date]);
 
Share this answer
 
v4
Comments
Member 13410460 19-Jul-20 8:04am    
Hi, Thank you for your answer, I tried the code and it says that the 'Datename function requires 2 arguments'
#realJSOP 19-Jul-20 8:06am    
My immediate answer is to be a programmer, learn how to use google, and fix it. Seriously, man...

I fixed the code.
Member 13410460 19-Jul-20 8:08am    
haha, I just replied to the results of YOUR code, that's all. But thank you
Member 13410460 19-Jul-20 10:31am    
The latest code is the one that gives me the number of days only in January, in the last code you only had to put the DATENAME(month,[Date]) in GROUP BY and it would be correct one, so please do it like this :
SELECT DATENAME(MONTH,[Date]) AS ForMonth
,COUNT(*) AS NumberOfDays
,YEAR([Date]) AS ForYearGR

FROM [dbo].[Expenses]
where [Date] IS NOT NULL
GROUP BY YEAR([Date]), MONTH([Date]), Datename(MOnth,[Date])

So it would match the question.

Thank you a lot , you helped me. !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900