I'm trying to check with sql if a date range (with start and end date) is in a month (regarding year). Month and year are given variables (GET-variables).
This is my table:
+----+------+-------+-----+
| id | name | start | end |
+----+------+-------+-----+
Because an appointment could be just one date (start and end would be the same date), I have to consider this.
My query
SELECT
id,
name,
start,
end
FROM appointments
WHERE (MONTH(start) = ? AND YEAR(end) = ?) OR (MONTH(start) = ? AND YEAR(end) = ?)
ORDER BY start
The problem with this query is that it just checks the start-month and the end-month not the months between. For example if an appointment is over 5 months, this query fails.
If you want to know if a particular month is in the range, then I would suggest turning the dates into a YYYYMM format. This makes the logic relatively easy to express:
where ?*100 + ? between year(start)*100 + month(start) and
year(end)*100 + month(end)
Related
Declare
#date1 date = '2015-12-01'
,#date2 date = '2015-12-30'
BEGIN
Declare #date_u char = Month(#date1)
,#date_v char = Month(#date2)
Select
STD.StoreNo As StoreNo
,CheckDate as Date
,ProductBarCode as ProductBarCode
,SUM( StocktakingQty)AS ProducQty
From StockTakingDetail STD
Inner Join
(Select StoreNo,CheckNo,CheckDate
From StockTakingMain SM )StocktakingMain
On STD.CheckNo =StockTakingMain.CheckNo
where year(CheckDate) between #date_u and #date_v
group By STD.StoreNo,STD.ProductBarCode,CheckDate
End
Actually, I want to show daily inventory, but once a month only.
They use to take inventory in the warehouse. I cannot able to fill dates gap without the data. So, I planned to use month and year only to get data . But, I can't be able to find a way how to take input parameter only month and year from date.
Can anyone help?
Do you want your where clause to look like this?
where year(CheckDate) * 100 + month(CheckDate) between year(#date1) * 100 + month(#date1) and
year(#date2) * 100 + month(#date2)
If so, I would really go fo:
where CheckDate >= date_sub(#date1, interval 1 - day(#date1)) and
CheckDate < date_add(date_sub(#date2, interval 1 - day(#date2)), interval 1 month)
I am stuck in a query, actually I have a search box which provide start datetime and end datetime, e.g. 2015-09-18 13:00:00 to 2015-09-21 17:00:00
I tried the query
select l.date, l.center_name, l.center_office, l.offline, l.online, l.category,
(select service_name from services_master where service_id = w.services) as servicename,
(select vendor_name from vendor_master where vendor_id = w.vendor) as vendorname
from lease_reports l,wan_entries w
where l.center_id = '7' and
w.id = l.center_id and
l.date between $startdatetime and $endatetime
I am not getting the exact result, result includes all the time between these two dates. I want day wise rows with exact interval time supplied by the user
The exact syntax will depend on what database you are using (see stackoverflow.com/questions/1658340/sql-query-to-group-by-day),
but the logic/pseudocode you are looking for is as follows.
...
AND day(l.date) BETWEEN day($startdatetime) and day($endatetime)
AND time(l.date) BETWEEN time($startdatetime) and time($endatetime)
GROUP BY day(l.date)
However, it might be clearer to the end user if you queried for date and time separately.
I have a MySQL table named 'events' that contains event data. The important columns are 'start' and 'end' which contain string (YYYY-MM-DD) to represent when the events starts and ends.
I want to get the records for all the active events in a time period.
Events:
------------------------------
ID | START | END |
------------------------------
1 | 2013-06-14 | 2013-06-14 |
2 | 2013-06-15 | 2013-08-21 |
3 | 2013-06-22 | 2013-06-25 |
4 | 2013-07-01 | 2013-07-10 |
5 | 2013-07-30 | 2013-07-31 |
------------------------------
Request/search:
Example: All events between 2013-06-13 and 2013-07-22 : #1, #3, #4
SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22' : #1, #2, #3, #4
SELECT id FROM events WHERE end BETWEEN '2013-06-13' AND '2013-07-22' : #1, #3, #4
====> intersect : #1, #3, #4
Example: All events between 2013-06-14 and 2013-06-14 :
SELECT id FROM events WHERE start BETWEEN '2013-06-14' AND '2013-06-14' : #1
SELECT id FROM events WHERE end BETWEEN '2013-06-14' AND '2013-06-14' : #1
====> intersect : #1
I tried many queries still I fail to get the exact SQL query.
Don't you know how to do that? Any suggestions?
Thanks!
If I understood correctly you are trying to use a single query, i think you can just merge your date search toghter in WHERE clauses
SELECT id
FROM events
WHERE start BETWEEN '2013-06-13' AND '2013-07-22'
AND end BETWEEN '2013-06-13' AND '2013-07-22'
or even more simply you can just use both column to set search time filter
SELECT id
FROM events
WHERE start >= '2013-07-22' AND end <= '2013-06-13'
You need the events that start and end within the scope. But that's not all: you also want the events that start within the scope and the events that end within the scope. But then you're still not there because you also want the events that start before the scope and end after the scope.
Simplified:
events with a start date in the scope
events with an end date in the scope
events with the scope startdate between the startdate and enddate
Because point 2 results in records that also meet the query in point 3 we will only need points 1 and 3
So the SQL becomes:
SELECT * FROM events
WHERE start BETWEEN '2014-09-01' AND '2014-10-13'
OR '2014-09-01' BETWEEN start AND end
Here lot of good answer but i think this will help someone
select id from campaign where ( NOW() BETWEEN start_date AND end_date)
SELECT id
FROM events
WHERE start <= '2013-07-22'
AND end >= '2013-06-13';
Or use MIN() and MAX() if you don't know the precedence.
SELECT *
FROM events
WHERE start <= '2013-07-22' OR end >= '2013-06-13'
SELECT *
FROM events
WHERE endDate >= #startDate AND startDate <= #endDate
For explanation refer to this diagram:
Suppose sample data is [startDate: 2020-10-01, endDate: 2020-20-01]
The user provides #startDate and #endDate to search
For overlap there are 4 scenarios and 1 variation (red/maroon lines)
For no overlap there are just 2 scenarios (green lines)
So, in order to get overlapping dates by providing start and end date, endDate must be greater than #startDate and startDate must be less than #endDate.
EDIT: I've squeezed the filter a lot. I couldn't wrap my head around it before how to make sure something really fit within the time period. It's this: Start date BEFORE the END of the time period, and End date AFTER the BEGINNING of the time period
With the help of someone in my office I think we've figured out how to include everyone in the filter.
There are 5 scenarios where a student would be deemed active during the time period in question:
1) Student started and ended during the time period.
2) Student started before and ended during the time period.
3) Student started before and ended after the time period.
4) Student started during the time period and ended after the time period.
5) Student started during the time period and is still active (Doesn't have an end date yet)
Given these criteria, we can actually condense the statements into a few groups because a student can only end between the period dates, after the period date, or they don't have an end date:
1) Student ends during the time period AND [Student starts before OR during]
2) Student ends after the time period AND [Student starts before OR during]
3) Student hasn't finished yet AND [Student starts before OR during]
(
(
student_programs.END_DATE >= '07/01/2017 00:0:0'
OR
student_programs.END_DATE Is Null
)
AND
student_programs.START_DATE <= '06/30/2018 23:59:59'
)
I think this finally covers all the bases and includes all scenarios where a student, or event, or anything is active during a time period when you only have start date and end date. Please, do not hesitate to tell me that I am missing something. I want this to be perfect so others can use this, as I don't believe the other answers have gotten everything right yet.
try this
SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22'
AND end BETWEEN '2013-06-13' AND '2013-07-22'
DEMO HERE
output :
ID
1
3
4
If you would like to use INTERSECT option, the SQL is as follows
(SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22')
INTERSECT
(SELECT id FROM events WHERE end BETWEEN '2013-06-13' AND '2013-07-22')
In PHP and phpMyAdmin
$tb = tableDataName; //Table name
$now = date('Y-m-d'); //Current date
//start and end is the fields of tabla with date format value (yyyy-m-d)
$query = "SELECT * FROM $tb WHERE start <= '".$now."' AND end >= '".$now."'";
If anyone is searching for a situation when the current date is residing between two periods (start/end date) in Microsoft SQL, please find below
select id from campaign where (getdate() BETWEEN start_date AND end_date)
I run a query against a MySQL database to get total number of visits grouped by week.
The structure of the table is:
|ID (int) | SESSION (char) | TIMESTAMP (datetime) |
My query looks like this:
'SELECT COUNT(session), WEEKOFYEAR(timestamp)
FROM stats
GROUP BY WEEKOFYEAR(timestamp)
ORDER BY timestamp ASC';
So I get an array of week numbers eg 40,41,45 etc, along with the view count.
How can I convert this into readable date (using PHP)? It's not practical to say, "Week number 40-something: 2000 visits".
I'm looking for something in the form of StartDate-EndDate/Month/Year, eg. Week 5-11/12/2011, Visits: XXXX.
Any functions you might have used before? I've tried but with no luck.
Is my SQL query a correct way to do it? Assuming that I'm querying the db correctly for what I'm trying to accomplish, is there a way to convert a week number into a day/date span?
I'm also wondering what will happen if a week spans between two months or even two years.
Assumptions:
The date you want to display is the Monday Week Date for that week
Your main output is Week <week number>-<monday date of week>, Visits: <count>.
You know enough PHP to be able to pull the column Phrase
The following SQL command should display for you the count of sessions per week of year, the week of year, and your desired phrase:
SELECT COUNT(session) AS VisitCount
, WEEKOFYEAR(timestamp) AS WeekOfYear_Value
, MAKEDATE(
CASE
WHEN WEEKOFYEAR(timestamp) = 52
THEN YEAR(timestamp)-1
ELSE YEAR(timestamp)
END, (WEEKOFYEAR(timestamp) * 7)-4) AS DateOfWeek_Value
, CONCAT('Week ', WEEKOFYEAR(timestamp)
, '-', MAKEDATE(
CASE
WHEN WEEKOFYEAR(timestamp) = 52
THEN YEAR(timestamp)-1
ELSE YEAR(timestamp)
END, (WEEKOFYEAR(timestamp) * 7)-4) -- Monday
, ', Visits: ' , COUNT(session), '.') AS Phrase
FROM stats
GROUP BY WEEKOFYEAR(timestamp)
ORDER BY timestamp ASC
Try it out on your existing data.
[edit : additional code changes]
To get you the Sunday output:
SELECT COUNT(session) AS VisitCount
, WEEKOFYEAR(timestamp) AS WeekOfYear_Value
, CONCAT('Week ', WEEKOFYEAR(timestamp)
, '-', MAKEDATE(
CASE
WHEN WEEKOFYEAR(timestamp) = 52
THEN YEAR(timestamp)-1
ELSE YEAR(timestamp)
END,
CASE
WHEN WEEKOFYEAR(timestamp) = 52
THEN (WEEKOFYEAR(timestamp) * 7)+3
ELSE (WEEKOFYEAR(timestamp) * 7)+2
END
)
, ', Visits: ' , COUNT(session), '.') AS Phrase
FROM stats
GROUP BY WEEKOFYEAR(timestamp)
ORDER BY timestamp ASC
Also notice that this last update includes another CASE in the makedate command, to ensure consistency between dates from the current and last year values.
I have mysql database and is full of over 2 years of data. How can I make a query in a way that it will get the result as below?:
January
Week 1
...
data rows here
....
Week 2
...
...
Week 3
...
...
Week 4
...
...
February (same as above)
These are the field structures:
- date (in yyyy-mm-dd format)
- job (integer autoincrement)
- person (varchar)
Try this, it will generate output pretty similar to one required by you
SELECT MONTH(date) AS MONTH, WEEK(date) AS WEEK, DATE_FORMAT(date, %Y-%m-%d) AS DATE, job AS JOB, person AS PERSON GROUP BY WEEK(date);
GROUP BY year(record_date), MONTH(record_date)
Check out the date and time functions in MySQL.
It has to be a query, or you can use ajax too? Using ajax you could do a loop in javascript:
date = [initial date]
while date <= [final date] {
divUpdate = 'divrecs'; // will be used in updateDiv function
url = 'getrecs.php?date1='+date+'&date2='+(date+6);
conecta(url,updateDiv);
date = date+7;
}
And inside getrecs your query would be:
$stmt = $dbh->prepare("select * from yourtable where date >= '".$_GET['date1']."' and date <= '".$_GET['date2']."'");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
echo "Do anything with your data here: $row[1] etc<BR>";
}
}
Hope that helps!
SELECT
MONTH(created_datetime) AS month,
WEEK(created_datetime) AS week,
DATE(created_datetime) AS date,
COUNT(id) AS count
FROM users
WHERE date(created_datetime) BETWEEN '2017-05-01' AND '2017-12-31'
GROUP BY month
ORDER BY created_datetime
If you want records date wise that you need to use GROUP BY date.
If you want records weekly that you need to use GROUP BY week.
If you want records monthly that you need to use GROUP BY month.