Number of sunday, monday, etc before current date in current month using Mysql Query

StackOverflow https://stackoverflow.com/questions/23107474

  •  04-07-2023
  •  | 
  •  

Pregunta

I have one date field inside table, and i want to find the number of sunday's before current date in current month using mysql.

How can i get the number of sunday, monday, etc before current date in current month ?

¿Fue útil?

Solución

You can get the no of Sundays in current month and your date column is less than to current date by using SUM with expression DAYNAME(created) ='sunday' ,using sum with expression will result in a boolean 0 or 1,also make sure you have stored the standard date object in your date field in my case i have used the name as created, and in where clause i have compared the date column with current month dates

SELECT 
IFNULL(SUM(DAYNAME(created) ='Sunday'),0) `sundays`
FROM `table`
WHERE  created > LAST_DAY(NOW() - INTERVAL 1 MONTH) 
 AND   created < CURRENT_DATE()

After question is edited you can also count no. days by their name as below for a period from month starting to current date

SELECT 
IFNULL(SUM(DAYNAME(created) ='Sunday'),0) `sundays`,
IFNULL(SUM(DAYNAME(created) ='Monday'),0) `mondays`,
IFNULL(SUM(DAYNAME(created) ='Tuesday'),0) `tuesdays`,
IFNULL(SUM(DAYNAME(created) ='Wednesday'),0) `wednesdays`,
IFNULL(SUM(DAYNAME(created) ='Thursday'),0) `thursdays`,
IFNULL(SUM(DAYNAME(created) ='Friday'),0) `fridays`,
IFNULL(SUM(DAYNAME(created) ='Saturday'),0) `saturdays`
FROM `table`
WHERE  created > LAST_DAY(NOW() - INTERVAL 1 MONTH) 
AND   created < CURRENT_DATE()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top