I have a table (Hire Rates) which contains multiple records. I'm trying to find records based on a date query but cannot get it to work correctly.
Essentially I am looking for records that contain a date between two dates. If my query date is "2021-08-15", it should return the third row (3000) as the query date falls between the two dates.
It is mostly working for me, except if the query date is equal to the start date or end date - in that case it doesn't return any result.
Table
startDate
endDate
hireRate
2021-01-01
2021-03-05
2350
2021-03-06
2021-04-08
2890
2021-04-09
2021-09-15
3000
Query
$sql = "SELECT rate, currencyID FROM hire_rates WHERE status = '1' AND NOT (startDate >= '$queryDate' OR endDate <= '$queryDate')
Try adding 'between' condition.
Like
select rate, currencyId from hire_rates where states =1 and not (cast($queryDate as DATE) between cast(startDate As DATE) and cast(endDate AS DATE) )
You would pass in the date you care about as a parameter. Then you can use between (based on your description of the logic):
SELECT rate, currencyID
FROM hire_rates
WHERE status = 1 AND
? BETWEEN startDate AND endDate;
Where ? is a parameter for the date you are passing in.
For 2021-08-15, you can write:
WHERE status = 1 AND
'2021-08-15' BETWEEN startDate AND endDate;
If you want the current date, you can actually get that from the database:
SELECT rate, currencyID
FROM hire_rates
WHERE status = 1 AND
curdate() BETWEEN startDate AND endDate;
Just try this then, `$sql = SELECT hireRate FROM hire_rate WHERE startDate<= '$queryDate' and endDate >= '$queryDate'
Related
I have a sms tracker database with a date column in the format 02/25/2018 04:12:52 pm. I want to count the no of sms sent each day to display it in bar chart.
I could only count sms sent by a user using this query "SELECT count(*) as user_count from table where username = 'CTC01'". How can i get an array of count for each day in a particular month
Since OP's date_column is VARCHAR type. We use STR_TO_DATE function:
SELECT DATE(STR_TO_DATE(date_column, "%m/%d/%Y %r")), COUNT(*)
FROM table
GROUP BY DATE(STR_TO_DATE(date_column, "%m/%d/%Y %r"));
Use DATE function, to convert a datetime expression to a date. Then use GROUP BY to get COUNT datewise.
In case, you want to get data for a specific user (eg: CTC01) and datewise. You can do the following:
SELECT DATE(STR_TO_DATE(date_column, "%m/%d/%Y %r")), COUNT(*)
FROM table
WHERE username = 'CTC01'
GROUP BY DATE(STR_TO_DATE(date_column, "%m/%d/%Y %r"));
I see your date format is 'm/d/Y H:i:s'. So, to get the total for each day in a month, you have to do a comparison against the least time in that month and the highest time in that month. So, the query for February 2018 would be:
SELECT DATE(date_column), COUNT(*)
FROM jobs
where created_on >= '02/01/2018 00:00:00' and created_on < '03/01/2018 00:00:00'
GROUP BY DATE(date_column);
To get for a particular user, simply append a where clause to the query above like so:
SELECT DATE(date_column), COUNT(*)
FROM jobs
where created_on >= '02/01/2018 00:00:00' and created_on < '03/01/2018 00:00:00' and username = 'CTC01'
GROUP BY DATE(date_column);
EDIT
Since your date column is varchar, you first have to convert it to datetime. So run this query instead:
SELECT DATE(DATE_FORMAT(STR_TO_DATE(date_column, '%c/%e/%Y %H:%i'), '%Y-%m-%d %H:%m:%s')) as Date, COUNT(*)
FROM jobs
where created_on >= '02/01/2018 00:00:00' and created_on < '03/01/2018 00:00:00'
GROUP BY DATE(DATE_FORMAT(STR_TO_DATE(date_column, '%c/%e/%Y %H:%i'), '%Y-%m-%d %H:%m:%s'));
first of all i want to extract dates of the relevant month from the database.for that i have used following query and i had generated the following output.
code
SELECT DISTINCT date as tot FROM attendance WHERE date LIKE '%2016-06%'
output
then i need to get the present employees for that dates from the database.but when i try that, it gives me total for one date only.how can i over come this.Here is my code.
SELECT DISTINCT date as days, COUNT(DISTINCT employee_id) as tot FROM attendance WHERE in_time != '' AND out_time != '' AND date LIKE '%2016-06%'
You need to use group by. mysql just returns an arbitrary value when you omit fields from the select list that are not included in aggregate functions. Then you can remove distinct:
SELECT date as days, COUNT(DISTINCT employee_id) as tot
FROM attendance
WHERE in_time != '' AND out_time != '' AND date LIKE '%2016-06%'
GROUP BY date
Per comment, what data type is your date field? Assuming it's a date, you could remove like and use year and month:
AND Month(date) = 6 AND Year(date) = 2016
I got a table with two columns, timestamp (like '1405184196') and value.
I've saved some measured values.
$day= time()-84600;
$result = mysql_query('SELECT timestamp, value FROM table WHERE timestamp >= "'.$day.'" ORDER BY timestamp ASC');
This is how I get all values for the last 24h.
But is it possible to get average day values for the last month with a SQL statement or do I have to select all values of the last month and calculate the average of each day via PHP?
Several issues with Anish's answer:
1) This won't work if date+time is being stored in the timestamp field.
2) It assumes the OP means last month i.e June, May etc and not the last say 30 days.
This solves those issues:
SELECT DATE(`timestamp`) as `timestamp`, AVG(value)
FROM table
WHERE `timestamp` >= CURDATE() - INTERVAL 1 MONTH
GROUP BY DATE(`timestamp)
EDIT
Since the timestamp is a unix timestamp and the OP would like a calendar month:
SELECT DATE(FROM_UNIX(`timestamp`)) as `timestamp`, AVG(value)
FROM table
WHERE MONTH(FROM_UNIX(`timestamp`)) = MONTH(NOW() - 1)
GROUP BY DATE(FROM_UNIX(`timestamp))
You can do this:-
SELECT timestamp, AVG(value)
FROM table
GROUP BY timestamp
HAVING MONTH(timestamp) = MONTH(NOW()) - 1;
This query calculates average for last month.
DEMO
I have a scenario where I need to pull up delivery dates based on a table below (Example)
job_id | delivery_date
1 | 2013-01-12
2 | 2013-01-25
3 | 2013-02-15
What I'm trying to do is show the user all the delivery dates that start with the earliest (in this case it would be 2013-01-12) and add an another 21 days to that. Basically, the output I would expect it to show of course, the earliest date being the starting date 2013-01-12 and 2013-01-25. The dates past the February date are of no importance since they're not in my 21 date range. If it were a 5 day range, for example, then of course 2013-01-25 would not be included and only the earliest date would appear.
Here is main SQL clause I have which only shows jobs starting this year forward:
SELECT date, delivery_date
FROM `job_sheet`
WHERE print_status IS NULL
AND job_sheet.date>'2013-01-01'
Is it possible to accomplish this with 1 SQL query, or must I go with a mix of PHP as well?
You can use the following:
select *
from job_sheet
where print_status IS NULL
and delivery_date >= (select min(delivery_date)
from job_sheet)
and delivery_date <= (select date_add(min(delivery_date), interval 21 day)
from job_sheet)
See SQL Fiddle with Demo
If you are worried about the dates not being correct, if you use a query then it might be best to pass in the start date to your query, then add 21 days to get the end date. Similar to this:
set #a='2013-01-01';
select *
from job_sheet
where delivery_date >= #a
and delivery_date <= date_add(#a, interval 21 day)
See SQL Fiddle with Demo
SELECT date,
delivery_date
FROM job_sheet
WHERE print_status IS NULL
AND job_sheet.date BETWEEN (SELECT MIN(date) FROM job_sheet) AND
(SELECT MIN(date) FROM job_sheet) + INTERVAL 21 DAY
SELECT j.job_id
, j.delivery_date
FROM `job_sheet` j
JOIN ( SELECT MIN(d.delivery_date) AS earliest_date
FROM `job_sheet` d
WHERE d.delivery_date >= '2013-01-01'
) e
ON j.delivery_date >= e.earliest_date
AND j.delivery_date < DATE_ADD(e.earliest_date, INTERVAL 22 DAY)
AND j.print_status IS NULL
ORDER BY j.delivery_date
(The original query has a predicate on job_sheet.date; the query above references the d.delivery_date... change that if it is supposed to be referencing the date column instaed.)
If the intent is to only show delivery_date values from today forward, then change the literal '2013-01-01' to an expression that returns the current date, e.g. DATE(NOW())
I want to be able to fetch results from mysql with a statement like this:
SELECT *
FROM table
WHERE amount > 1000
But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
...$m being a month but it gave error.
In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?
You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(dateStart) = {$m}
Caveats:
Mind that you are using mysql_escape_string or you risk SQL injection attacks.
Function calls on columns means that an index, if one exists, can not be used
Alternatives:
Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:
WHERE startdate BETWEEN STR_TO_DATE([start_date], [format])
AND STR_TO_DATE([end_date], [format])
See the documentation for formatting syntax.
Reference:
MONTH
YEAR
BETWEEN
STR_TO_DATE
Use the month() function.
select month(now());
Try this:
SELECT *
FROM table
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')
E.g.
$date = sprintf("'%04d-%02d-01'", $year, $month);
$query = "
SELECT
x,y,dateStart
FROM
tablename
WHERE
AND amount > 1000
AND dateStart >= $date
AND dateStart < $date+Interval 1 month
";
mysql_query($query, ...
This will create a query like e.g.
WHERE
AND amount > 1000
AND dateStart >= '2010-01-01'
AND dateStart < '2010-01-01'+Interval 1 month
+ Interval 1 month is an alternative to date_add().
SELECT Date('2010-01-01'+Interval 1 month)-> 2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)-> 2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.
Try this
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(datestart)
GROUP BY EXTRACT(YEAR_MONTH FROM datestart)
Try this if(date field is text then convert this string to date):
SELECT * FROM `table_name` WHERE MONTH(STR_TO_DATE(date,'%d/%m/%Y'))='11'
//This will give month number MONTH(STR_TO_DATE(date,'%d/%m/%Y'))
//If its return 11 then its November
// Change date format with your date string format %d/%m/%Y
Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
Day:
SELECT EXTRACT(DAY FROM "2017-06-15");
Month:
SELECT EXTRACT(MONTH FROM "2017-06-15");
Year:
SELECT EXTRACT(YEAR FROM "2017-06-15");