count on date between - mysql

table food
"Expire date"food name
"2010-01-01"porato
"2011-01-01"tomamto
"2013-01-01"chips
"2011-01-04"orange
"2017-01-01"banana
i wanna use select to get out how much food expire in date between 2010-01-01 to 2013-12-30
so the out should be like
2010 1
2011 2
2013 1
i try
select foodName,ExpireDate
from food
where ExpireDate between '2010-01-01' and '2013-12-30'
but not work

If you want the results by year, you need aggregation:
select year(ExpireDate) as year, count(*)
from food
where ExpireDate between '2010-01-01' and '2013-12-30'
group by year(ExpireDate);
Note: It seems odd that you are skipping the last day or two of 2013 (depending on whether ExpireDate has a time component). More typical logic would be:
select year(ExpireDate) as year, count(*)
from food
where ExpireDate >= '2010-01-01' and
ExpireDate < '2014-01-01'
group by year(ExpireDate);

Related

Getting the number of users for this year and last year in SQL

My table is like this:
root_tstamp
userId
2022-01-26T00:13:24.725+00:00
d2212
2022-01-26T00:13:24.669+00:00
ad323
2022-01-26T00:13:24.629+00:00
adfae
2022-01-26T00:13:24.573+00:00
adfa3
2022-01-26T00:13:24.552+00:00
adfef
...
...
2021-01-26T00:12:24.725+00:00
d2212
2021-01-26T00:15:24.669+00:00
daddfe
2021-01-26T00:14:24.629+00:00
adfda
2021-01-26T00:12:24.573+00:00
466eff
2021-01-26T00:12:24.552+00:00
adfafe
I want to get the number of users in the current year and in previous year like below using SQL.
Date Users previous_year
2022-01-01 10 5
2022-01-02 20 15
The code is written as follows.
select CAST(root_tstamp as DATE) as Date,
count(DISTINCT userid) as users,
count(Distinct case when CAST(root_tstamp as DATE) = dateadd(MONTH,-12,CAST(root_tstamp as DATE)) then userid end) as previous_year
FROM table1
But it returns 0 for previous_year values.
How can I fix that?
Possible solution for SQL Server:
WITH cte AS ( SELECT 2022 [year]
UNION ALL
SELECT 2021 )
SELECT cte.[year],
COUNT(DISTINCT test.userId) current_users_amount,
COUNT(DISTINCT CASE WHEN YEAR(test.root_tstamp) < cte.[year]
THEN test.userId
END) previous_users_amount
FROM test
JOIN cte ON YEAR(test.root_tstamp) <= cte.[year]
GROUP BY cte.[year]
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=88b78aad9acd965bdbac4c85a0b81927
This query (for MySql) returns unique number of userids where the root_timestamp is in the current year, by day, and the number of unique userids for the same day last year. If there is no record for a day in the current year nothing will be displayed for that day. If there are rows for the current year, but no rows for the same day last year, then NULL will be shown for that lastyear column.
SELECT cast(ty.root_tstamp as date) as Dte,
COUNT(DISTINCT ty.userId) as users_this_day,
count(distinct lysd.userid) as users_sameday_lastyear
FROM test ty
left join
test lysd
on cast(lysd.root_tstamp as date)=date_add(cast(ty.root_tstamp as date), interval -1 year)
WHERE YEAR(ty.root_tstamp) = year(current_date())
GROUP BY Dte
If you wish to show output rows for calendar days even if there are no rows in current year and/or last year, then you also need a calendar table to be introduced (let's hope that it is not what you need)

Get count of departmant with total employees for period of month in mysql

I have requirement to get count of distinct department with total employees in period of month but unfortunately query is not working and throwing error
My table
Department_id emloyee_id date_time
1 1 2020-02-01
1 2 2020-02-04
3 7 2020-02-06
1 4 2020-02-07
expected output
total department=2
total employee of all department=4
But all should work based on last one record , I am getting sql syntax error
Query:
SELECT COUNT(DISTINCT department_id) x, COUNT(*) y
FROM department
WHERE date_time>=DATE_FORMAT(NOW() ,'%Y-%m-01')
AND date_time<DATE(NOW()+INTERVAL 1 DAY and status='1'
You can combine them within only one query :
SELECT COUNT(DISTINCT Department_id), COUNT(DISTINCT employee_id)
FROM department
WHERE date_time >= NOW() - INTERVAL 1 MONTH
AND status = '1';
counting both distinctly.
Update : If you mean to stay within the current month, then also
AND date_time>=DATE_FORMAT(NOW() ,'%Y-%m-01')
might be added to this query as in your original one.
It seems you should use month instead of day and are missing a bracket after month
SELECT COUNT(DISTINCT department_id) AS departments,
COUNT(*) AS employees
FROM department
WHERE date_time>=DATE_FORMAT(NOW() ,'%Y-%m-01')
AND date_time < DATE(NOW()+INTERVAL 1 MONTH)
AND status = '1';

Modify SQL query to get data only from past 2 months

Please help me modify the following query to extract only records made in the past 2 months.
SELECT COUNT(*)
FROM course_participants
WHERE course_id = courses.id
WHERE YEAR(created) = 2019)
Now it gets results from current year, I need to get the results from the past 2 months.
Thanks!
You can try below -
SELECT COUNT(*) FROM course_participants
WHERE created>=now()-interval 2 month
You can use the Month-function:
SELECT
COUNT(*)
FROM
course_participants
WHERE
course_id = courses.id and
YEAR(created) = 2019 and
MONTH(created) in (4,5)
If the date should not be fix, but depend on the current date. you can check out the Dateadd-Function.
If you want your query to return records from the past two months dynamically, then you can add a DATE_ADD expression in your WHERE clause:
SELECT COUNT(*) FROM course_participants WHERE course_id = courses.id and
created > DATE_ADD(CURDATE(), INTERVAL -2 MONTH)
This takes the current date and goes back 2 months. You can see some documentation on the function here.
You can substract 2 months from the current date.
SELECT COUNT(*) FROM course_participants WHERE course_id = courses.id AND created >= DATE_SUB(CURRENT_DATE, INTERVAL 2 MONTH)

MySQL: COUNT with multible GROUP BY

I have a table storing weatherdata in 5min intervals.
Now I need result with total raindays grouped by Year like this:.
2010 100 raindays
2011 120 raindays
2013 90 raindays
This is my current query:
SELECT date, SUM(rain) FROM $tableName GROUP BY date HAVING SUM(rain) > 0";
as expected, this gives me following result:
2010-01-02 1.2 (mm)
2010-01-05 1.6 (mm)
2010-02-10 2.6 (mm)
How I have to change my query, to have this grouped by year(date) and counted days ?
Thanks all for your help
PM
You can group by YEAR(date), to sum the rain grouped by year. Then to count the number of days you can COUNT DISTINCT the days without the time part, using DATE(date) function.
SELECT YEAR(date), SUM(rain), COUNT(DISTINCT DATE(date)) days
FROM $tableName
WHERE rain>0
GROUP BY YEAR(date)
Please see fiddle here.
The following query might help you if you want to find maximum element is each group,
select
e.date, e.rain
from
TableName e
join
(select
date, MAX(rain) MS
from
TableName
group by date
Having rain > 0) m ON e.date = M.date and e.rain = m.rain

MySQL : Count row where sum of left day is less than 30

I want to count the users in the table who's subscriptions are going to expire within a month (30 days). Here is my code:
user_db
id name exp_date
1 John 2013-03-01
2 Alice 2013-02-25
3 Ken 2013-01-10
4 Elise 2013-04-11
5 Bruce 2013-03-14
According to the DB above. There should be 3 persons whom their subscription is about to be expired - John, Alice and Bruce. I don't want Ken to be counted because he doesn't want to subscribe for more.
Here's my MySQL code:
SELECT count(id) AS exp_pax,
datediff(exp_date,now()) AS day_left
FROM labour_db
WHERE day_left<=30
Well, the code does selects only a row in which the sum of day less than 30 but it doesn't count. So please you guy suggest me.
Regards,
If you want to count all records where (1) the expiration date is within 30 days of now and (2) the expiration date is not before now, then use
SELECT count(*) AS exp_pax
FROM user_db
WHERE exp_date<=timestampadd(day, 30, now())
AND exp_date >= now();
If that's the case then you need to add condition wherein it checks if the exp_date is less than today.
SELECT COUNT(*) totalCount
FROM user_db
where exp_date <= timestampadd(day, 30, now()) AND
exp_date > NOW()
SQLFiddle Demo
Remove the group by id to get your count.
Count will roll up rows, as you expect, but when combined with a group by clause, will count each "group". You could use this usefully, for instance, to group by expiration date.