[英]SQL Query to select Specific Month in MYSQL Database
I have a database where I have date field 2020-08-03我有一个数据库,其中有日期字段 2020-08-03
I am trying to get the data for each month我正在尝试获取每个月的数据
SELECT COUNT(*) FROM new_caseWHERE sla_client = 'ITA' AND MONTH(sysdate) = MONTH(current_date ())
AND YEAR(sysdate) = YEAR(current_date())
The above works for the current month and year what would I use to query in the above for January 2020, February 2020 and so on以上适用于当前月份和年份我将使用什么在上面查询 2020 年 1 月、2020 年 2 月等
I think that you want aggregation:我认为你想要聚合:
select
date_format(mydate, '%Y-%m') yyyy_mm,
count(*) cnt
from new_case
where sla_client = 'ITA'
group by date_format(mydate, '%Y-%m')
order by yyyy_mm
This gives you one row per month, with the count of rows in that month (if there is no data for a given month, then it just does not appear in the resultset).这为您每月提供一行,其中包含该月的行数(如果给定月份没有数据,则它不会出现在结果集中)。
If you need to filter on a given date range, then I would recommend using a where
clause that filters directly on the date values rather than applying date functions.如果您需要过滤给定的日期范围,那么我建议使用直接过滤日期值而不是应用日期函数的
where
子句。 Say you want the last 3 months and the current month, then:假设您想要过去 3 个月和当前月份,然后:
select
date_format(mydate, '%Y-%m') yyyy_mm,
count(*) cnt
from new_case
where
sla_client = 'ITA'
and mydate >= date_format(current_date, '%Y-%m-01') - interval 3 month
and mydate < date_format(current_date, '%Y-%m-01') + interval 1 month
group by date_format(mydate, '%Y-%m')
order by yyyy_mm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.