Supposed I have data as below:
id | cnt | insert_time |
---|---|---|
1 | 234 | 1679131273 |
2 | 12 | 1679131273 |
3 | 80 | 1679131514 |
4 | 30 | 1679131514 |
5 | 124 | 1679131605 |
6 | 4.3 | 1679131605 |
7 | 4 | 1679131935 |
8 | 1.5 | 1679131935 |
9 | 5 | 1679292635 |
10 | 56 | 1679292635 |
I can use the below SQL
to get data of weeks
, but I don’t need a list(and the data of week’s first day is Sunday, not Monday), I just need the current week, and it’s from Monday to now, how to query current week and month data with SQL
in MySQL?(week data from monday, and month data from first day of the month)
SELECT CONCAT(YEAR(FROM_UNIXTIME(created_at,'%Y-%m-%d')), '/', WEEK(FROM_UNIXTIME(created_at,'%Y-%m-%d'))) as weeks
,id
,sum(cnt) as total_cnt
FROM project
GROUP BY weeks,uid
ORDER BY weeks desc,total_cnt desc
Thanks so much for any advice.
2
Answers
If you want the sum of all counts for the current month, you can use a
where
clause:Rationale :
current_date
returns the current system datedate_format(..., '%Y-%m-01')
truncates to the first day of the monthunix_timestamp
turns the results to a unix timestamp, that you can use to filter your columnIf you wanted the current week:
weekday(current_date)
returns the index of the current date (0 for Monday, 1 for Tuesday, …), which we can use to offset the date to Monday.Related reading: MySQL Date and Time functions.
I think this will provide the answer you are looking for:
I am not using
WEEK()
in this query but thought it useful to reference this as you mentioned it in your question.WEEK(date[,mode])
WEEKEDAY(date)
You need to be aware of implicit conversion between session timezone and UTC when using
FROM_UNIXTIME()
andUNIX_TIMESTAMP()
.