SQL check record in between two dates and time - sql-server-2008

I have table i.e. BookingDetails. BookingDetails containt following fields.
CustomerID
DateFrom
DateTo
TimeFrom
TimeTo
BookingDetails contains n records.
CustomerID DateFrom DateTo TimeFrom TimeTo
11137 2012-08-14 2012-08-16 00:33:46 03:33:46
11138 2012-08-15 2012-08-17 08:00:00 00:31:03
11139 2012-08-16 2012-08-17 22:46:25 00:46:25
I want to select records between given information DateFrom, DateTo, TimeFrom, TimeTo.
I have do following query
declare #fDate date
set #fDate = '2012-08-14'
declare #tDate date
set #tDate = '2012-08-16'
declare #fTime time
set #fTime ='12:33:46 AM'
declare #tTime time
set #tTime='12:31:03 AM'
SELECT BookingDetails.CustomerID
FROM BookingDetails
WHERE (DateFrom between #fDate and #tDate) And (BookingDetails.DateFrom >= #fDate and BookingDetails.DateTo<=#tDate)
and(TimeFrom between CONVERT(varchar(15),cast(#fTime as time) , 108) and CONVERT(varchar(15),cast(#tTime as time) , 108))
and (TimeFrom >=CONVERT(varchar(15),cast(#fTime as time) , 108) and TimeTo <=CONVERT(varchar(15),cast(#tTime as time) , 108))
Time save in database is in 24 hours format. Time used in query is 12Hours format thats why i convert it to 24 hours format in query.
Is this query is correct or I have to change it?
This Query doesn't return any value. I want to select records between #fDate , #tDate, #fTime, #tTime
I expect Result for first two customerID i.e. 11137,11138

Why not pass the start and end as DATETIME instead of as separate values? In fact, why are you storing DATE and TIME separately when it's clear these are points in time and the two values are more important together than apart? Anyway given the current schema you need to stop converting to string. Try this:
DECLARE #b TABLE (
CustomerID INT,
DateFrom DATE,
DateTo DATE,
TimeFrom TIME,
TimeTo TIME
);
INSERT #b VALUES (11137,'2012-08-14','2012-08-16','00:33:46','03:33:46'),
(11138,'2012-08-15','2012-08-17','08:00:00','00:31:03'),
(11139,'2012-08-16','2012-08-17','22:46:25','00:46:25');
declare #fDate date
set #fDate = '2012-08-14'
declare #tDate date
set #tDate = '2012-08-16'
declare #fTime time
set #fTime ='12:33:46 AM'
declare #tTime time
set #tTime='12:31:03 AM'
;WITH x AS
(
SELECT
CustomerID, DateFrom, TimeFrom, DateTo, TimeTo,
[Start] = DATEADD(SECOND, DATEDIFF(SECOND,'00:00',TimeFrom),
CONVERT(DATETIME, DateFrom)),
[End] = DATEADD(SECOND, DATEDIFF(SECOND,'00:00',TimeTo),
CONVERT(DATETIME, DateTo))
FROM #b
)
SELECT * FROM x WHERE [Start]
BETWEEN CONVERT(DATETIME, #fDate) + CONVERT(DATETIME, #fTime)
AND CONVERT(DATETIME, #tDate) + CONVERT(DATETIME, #tTime);

Related

convert int to date to add a dayn and convert to int back

I have int value with YYYYMM. I want to:
1. convert it into datetime
2. add one day DATEADD(Day, +1, #date)
3. convert it back into int
What's the easiest way to do this?
Here is a nice exercise and I hope it works out for you...
declare #date date
declare #newDate date
set #date = convert(date, '20100101')
set #newdate = DateAdd(dd, 1, #Date)
select #date
select #newdate
select convert(int, convert(varchar, #newdate, 112)) -- this is your final conversion back to int
If your initial int is, say, 201310 (October 2013), then what I think you want is this:
select convert(datetime, rtrim(201310 * 100 + 1))
The function RTRIM is a trick to convert int to string type.
The result is this:
2013-10-01 00:00:00.000
If you don't want to use RTRIM, the command below will get you the same result:
select convert(datetime, convert(char, 201310 * 100 + 1))

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

I have a SQL Server table that has a "Time" column. The table is a log table the houses status messages and timestamps for each message. The log table is inserted into via a batch file. There is an ID column that groups rows together. Each time the batch file runs it initializes the ID and writes records. What I need to do is get the elapsed time from the first record in an ID set to the last record of the same ID set. I started toying with select Max(Time) - Min(Time) from logTable where id = but couldn't figure out how to format it correctly. I need it in HH:MM:SS.
SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.
create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
Values were chosen in such a way that for
id = 1, elapsed time is 1 hour
id = 2, elapsed time is 2 hours, and
id = 3, elapsed time is 3 hours.
This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.
select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
Note the misleading "03:00:00" for the 27-hour difference on id number 3.
Function to format elapsed time in SQL Server
UPDATED:
Correctly calculate a timespan in SQL Server, even if more than 24 hours:
-- Setup test data
declare #minDate datetime = '2012-12-12 20:16:47.160'
declare #maxDate datetime = '2012-12-13 15:10:12.050'
-- Get timespan in hh:mi:ss
select cast(
(cast(cast(#maxDate as float) - cast(#minDate as float) as int) * 24) /* hours over 24 */
+ datepart(hh, #maxDate - #minDate) /* hours */
as varchar(10))
+ ':' + right('0' + cast(datepart(mi, #maxDate - #minDate) as varchar(2)), 2) /* minutes */
+ ':' + right('0' + cast(datepart(ss, #maxDate - #minDate) as varchar(2)), 2) /* seconds */
-- Returns 18:53:24
Edge cases that show inaccuracy are especially welcome!
DECLARE #EndTime AS DATETIME, #StartTime AS DATETIME
SELECT #StartTime = '2013-03-08 08:00:00', #EndTime = '2013-03-08 08:30:00'
SELECT CAST(#EndTime - #StartTime AS TIME)
Result: 00:30:00.0000000
Format result as you see fit.
The best and simple way:
Convert(varchar, {EndTime} - {StartTime}, 108)
Just like Anri noted.
Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...
DATEDIFF(interval, date1, date2)
interval REQUIRED - The time/date part to return. Can be one of the following values:
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
date1, date2 REQUIRED - The two dates to calculate the difference between
select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...
See if this helps. I can set variables for Elapsed Days, Hours, Minutes, Seconds.
You can format this to your liking or include in a user defined function.
Note: Don't use DateDiff(hh,#Date1,#Date2). It is not reliable! It rounds in unpredictable ways
Given two dates...
(Sample Dates: two days, three hours, 10 minutes, 30 seconds difference)
declare #Date1 datetime = '2013-03-08 08:00:00'
declare #Date2 datetime = '2013-03-10 11:10:30'
declare #Days decimal
declare #Hours decimal
declare #Minutes decimal
declare #Seconds decimal
select #Days = DATEDIFF(ss,#Date1,#Date2)/60/60/24 --Days
declare #RemainderDate as datetime = #Date2 - #Days
select #Hours = datediff(ss, #Date1, #RemainderDate)/60/60 --Hours
set #RemainderDate = #RemainderDate - (#Hours/24.0)
select #Minutes = datediff(ss, #Date1, #RemainderDate)/60 --Minutes
set #RemainderDate = #RemainderDate - (#Minutes/24.0/60)
select #Seconds = DATEDIFF(SS, #Date1, #RemainderDate)
select #Days as ElapsedDays, #Hours as ElapsedHours, #Minutes as ElapsedMinutes, #Seconds as ElapsedSeconds
Hope this helps you in getting the exact time between two time stamps
Create PROC TimeDurationbetween2times(#iTime as time,#oTime as time)
As
Begin
DECLARE #Dh int, #Dm int, #Ds int ,#Im int, #Om int, #Is int,#Os int
SET #Im=DATEPART(MI,#iTime)
SET #Om=DATEPART(MI,#oTime)
SET #Is=DATEPART(SS,#iTime)
SET #Os=DATEPART(SS,#oTime)
SET #Dh=DATEDIFF(hh,#iTime,#oTime)
SET #Dm = DATEDIFF(mi,#iTime,#oTime)
SET #Ds = DATEDIFF(ss,#iTime,#oTime)
DECLARE #HH as int, #MI as int, #SS as int
if(#Im>#Om)
begin
SET #Dh=#Dh-1
end
if(#Is>#Os)
begin
SET #Dm=#Dm-1
end
SET #HH = #Dh
SET #MI = #Dm-(60*#HH)
SET #SS = #Ds-(60*#Dm)
DECLARE #hrsWkd as varchar(8)
SET #hrsWkd = cast(#HH as char(2))+':'+cast(#MI as char(2))+':'+cast(#SS as char(2))
select #hrsWkd as TimeDuration
End

Rounding datetime to quarter minutes

I have a function to round a datetime to the nearest quarter hour.
But is there a method to round down to the nearest quarter instead?
Example.
08:14:00 becomes 08:00:00
08:03:00 becomes 08:00:00
08:29:00 becomes 08:15:00
08:55:00 becomes 08:45:00
This is what I have now to round to the nearest quarter.
(
#dt datetime
)
returns datetime
as
begin
declare #result datetime
declare #mm int
set #mm=datepart(minute,#dt)
set #result = dateadd(minute,-#mm + (round(#mm/cast(15 as float),0)*15) , #dt )
return #result
Using SQL Server:
select cast(
FLOOR( cast( GetDate() as float)*(24*4)) / (24*4)
as smalldatetime) AS "datetime_quarter"
The strategy is:
Convert the date to a float number, *24 to get number of hours, *4 to get number of quarters
Round down with FLOOR
Convert back to number of days by /(24*4)
Convert number of days to a datetime. smalldatetime is used to avoid float rounding issues.
This can easily be adjusted to use ROUNDor CEILING instead; or to use other hour multiples instead of 4 (quarters).
This is a procedure to get the current quarter upper and lower bound.
declare QUARTER_FLOOR datetime;
declare QUARTER_CEIL datetime;
declare CURRENT_DATETIME datetime;
declare CURRENT_MINUTE int;
// get current datetime without second and millisecond
SET CURRENT_DATETIME = dateformat(getdate(), 'YYYY-MM-DD hh:NN:00.000');
set CURRENT_MINUTE = datepart(minute,CURRENT_DATETIME); // get current minute
// GET CURRENT QUARTER FLOOR
set QUARTER_FLOOR = dateadd(minute, -CURRENT_MINUTE + (round(CURRENT_MINUTE/cast(15 as float),0)*15) , CURRENT_DATETIME );
// GET CURRENT QUARTER FLOOR
set QUARTER_CEIL = dateadd(minute, ((round(CURRENT_MINUTE/cast(15 as float),0)+1)*15) - CURRENT_MINUTE , CURRENT_DATETIME );
// RETURN
select QUARTER_FLOOR, QUARTER_CEIL;
This method relies on integer division when we divide the month by 4. In principle it should be portable, subject of course to modifying the syntax of dateadd() / date_add() and month()/year().
SELECT DATEADD(
MONTH,
3 * (
MONTH( my_date ) / 4
),
CONCAT(
YEAR( my_date ),
'0101' )
) AS my_date_rounded_to_quarter

Difference between two dates in MySQL

How to calculate the difference between two dates, in the format YYYY-MM-DD hh: mm: ss and to get the result in seconds or milliseconds?
SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59, the difference in HH:MM:SS format
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
-- result: 79259 the difference in seconds
So, you can use TIMESTAMPDIFF for your purpose.
If you are working with DATE columns (or can cast them as date columns), try DATEDIFF() and then multiply by 24 hours, 60 min, 60 secs (since DATEDIFF returns diff in days). From MySQL:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
for example:
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30 00:00:00') * 24*60*60
Get the date difference in days using DATEDIFF
SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
| 17 |
+------+
OR
Refer the below link
MySql difference between two timestamps in days?
SELECT TIMESTAMPDIFF(HOUR,NOW(),'2013-05-15 10:23:23')
calculates difference in hour.(for days--> you have to define day replacing hour
SELECT DATEDIFF('2012-2-2','2012-2-1')
SELECT TO_DAYS ('2012-2-2')-TO_DAYS('2012-2-1')
select
unix_timestamp('2007-12-30 00:00:00') -
unix_timestamp('2007-11-30 00:00:00');
If you want to add where clause with DATEDIFF then it is also possible to add where clause or condition.
Take a look of following example.
select DATEDIFF(now(), '2022-08-12 17:55:51.000000') from properties p WHERE p.property_name = 'KEY';
Result : 6
SELECT TIMESTAMPDIFF(SECOND,'2018-01-19 14:17:15','2018-01-20 14:17:15');
Second approach
SELECT ( DATEDIFF('1993-02-20','1993-02-19')*( 24*60*60) )AS 'seccond';
CURRENT_TIME() --this will return current Date
DATEDIFF('','') --this function will return DAYS and in 1 day there are 24hh 60mm 60sec
Or, you could use TIMEDIFF function
mysql> SELECT TIMEDIFF('2000:01:01 00:00:00', '2000:01:01 00:00:00.000001');
'-00:00:00.000001'
mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001' , '2008-12-30 01:01:01.000002');
'46:58:57.999999'
This function takes the difference between two dates and shows it in a date format yyyy-mm-dd. All you need is to execute the code below and then use the function. After executing you can use it like this
SELECT datedifference(date1, date2)
FROM ....
.
.
.
.
DELIMITER $$
CREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE
NO SQL
BEGIN
DECLARE dif DATE;
IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0 THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),
'%Y-%m-%d');
ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
ELSE
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
END IF;
RETURN dif;
END $$
DELIMITER;
select TO_CHAR(TRUNC(SYSDATE)+(to_date( '31-MAY-2012 12:25', 'DD-MON-YYYY HH24:MI')
- to_date( '31-MAY-2012 10:37', 'DD-MON-YYYY HH24:MI')),
'HH24:MI:SS') from dual
-- result : 01:48:00
OK it's not quite what the OP asked, but it's what I wanted to do :-)
This code calculate difference between two dates in yyyy MM dd format.
declare #StartDate datetime
declare #EndDate datetime
declare #years int
declare #months int
declare #days int
--NOTE: date of birth must be smaller than As on date,
--else it could produce wrong results
set #StartDate = '2013-12-30' --birthdate
set #EndDate = Getdate() --current datetime
--calculate years
select #years = datediff(year,#StartDate,#EndDate)
--calculate months if it's value is negative then it
--indicates after __ months; __ years will be complete
--To resolve this, we have taken a flag #MonthOverflow...
declare #monthOverflow int
select #monthOverflow = case when datediff(month,#StartDate,#EndDate) -
( datediff(year,#StartDate,#EndDate) * 12) <0 then -1 else 1 end
--decrease year by 1 if months are Overflowed
select #Years = case when #monthOverflow < 0 then #years-1 else #years end
select #months = datediff(month,#StartDate,#EndDate) - (#years * 12)
--as we do for month overflow criteria for days and hours
--& minutes logic will followed same way
declare #LastdayOfMonth int
select #LastdayOfMonth = datepart(d,DATEADD
(s,-1,DATEADD(mm, DATEDIFF(m,0,#EndDate)+1,0)))
select #days = case when #monthOverflow<0 and
DAY(#StartDate)> DAY(#EndDate)
then #LastdayOfMonth +
(datepart(d,#EndDate) - datepart(d,#StartDate) ) - 1
else datepart(d,#EndDate) - datepart(d,#StartDate) end
select
#Months=case when #days < 0 or DAY(#StartDate)> DAY(#EndDate) then #Months-1 else #Months end
Declare #lastdayAsOnDate int;
set #lastdayAsOnDate = datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#EndDate),0)));
Declare #lastdayBirthdate int;
set #lastdayBirthdate = datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#StartDate)+1,0)));
if (#Days < 0)
(
select #Days = case when( #lastdayBirthdate > #lastdayAsOnDate) then
#lastdayBirthdate + #Days
else
#lastdayAsOnDate + #Days
end
)
print convert(varchar,#years) + ' year(s), ' +
convert(varchar,#months) + ' month(s), ' +
convert(varchar,#days) + ' day(s) '
If you've a date stored in text field as string you can implement this code it will fetch the list of past number of days a week, a month or a year sorting:
SELECT * FROM `table` WHERE STR_TO_DATE(mydate, '%d/%m/%Y') < CURDATE() - INTERVAL 30 DAY AND STR_TO_DATE(date, '%d/%m/%Y') > CURDATE() - INTERVAL 60 DAY
//This is for a month
SELECT * FROM `table` WHERE STR_TO_DATE(mydate, '%d/%m/%Y') < CURDATE() - INTERVAL 7 DAY AND STR_TO_DATE(date, '%d/%m/%Y') > CURDATE() - INTERVAL 14 DAY
//This is for a week
%d%m%Y is your date format
This query display the record between the days you set there like: Below from last 7 days and Above from last 14 days so it would be your last week record to be display same concept is for month or year. Whatever value you're providing in below date like: below from 7-days so the other value would be its double as 14 days. What we are saying here get all records above from last 14 days and below from last 7 days. This is a week record you can change value to 30-60 days for a month and also for a year.
Thank You Hope it will help someone.
You would simply do this:
SELECT (end_time - start_time) FROM t; -- return in Millisecond
SELECT (end_time - start_time)/1000 FROM t; -- return in Second
Why not just
Select Sum(Date1 - Date2) from table
date1 and date2 are datetime

Create a date range in mysql

Best way to create on the fly, date ranges, for use with report.
So I can avoid empty rows on my report if there's no activity for a given day.
Mostly to avoid this issue: What is the most straightforward way to pad empty dates in sql results (on either mysql or perl end)?
My advice is: don't make your life harder, make it easier. Just create a table with one row for each calendar day, having as many rows as you think you reasonably need to last. In datawarehousing, this is the common solution, and it is so widely implemented this way that a dwh that doesn't have it, has a code smell.
Many people used to dealing with more traditional oltp/data entry apps feel a natural revulsion against this idea, because the feel the can generate the data anyway, and therefore it shouldn't be stored. But if you do create a table like that, you can adorn it with many useful attributes, such as whether it's a holdiday or a weekend, and you can store many common date representations (iso, european, us format etc) inside it, which can save you a ton of time when creating reports (since you don't have to bother figuring out how the date formatting works in each reporting tool you come by. Or you can go a step further and update your date table everyday to mark flags for the current day, current week, current month, current year, etc - all kinds of useful tools that make it much, much easier to build reports that need to work against some date range.
MySQL sample code as per request in comment:
delimiter //
DROP PROCEDURE IF EXISTS p_load_dim_date
//
CREATE PROCEDURE p_load_dim_date (
p_from_date DATE
, p_to_date DATE
)
BEGIN
DECLARE v_date DATE DEFAULT p_from_date;
DECLARE v_month tinyint;
CREATE TABLE IF NOT EXISTS dim_date (
date_key int primary key
, date_value date
, date_iso char(10)
, year smallint
, quarter tinyint
, quarter_name char(2)
, month tinyint
, month_name varchar(10)
, month_abbreviation varchar(10)
, week char(2)
, day_of_month tinyint
, day_of_year smallint
, day_of_week smallint
, day_name varchar(10)
, day_abbreviation varchar(10)
, is_weekend tinyint
, is_weekday tinyint
, is_today tinyint
, is_yesterday tinyint
, is_this_week tinyint
, is_last_week tinyint
, is_this_month tinyint
, is_last_month tinyint
, is_this_year tinyint
, is_last_year tinyint
);
WHILE v_date < p_to_date DO
SET v_month := month(v_date);
INSERT INTO dim_date(
date_key
, date_value
, date_iso
, year
, quarter
, quarter_name
, month
, month_name
, month_abbreviation
, week
, day_of_month
, day_of_year
, day_of_week
, day_name
, day_abbreviation
, is_weekend
, is_weekday
) VALUES (
v_date + 0
, v_date
, DATE_FORMAT(v_date, '%y-%c-%d')
, year(v_date)
, ((v_month - 1) DIV 3) + 1
, CONCAT('Q', ((v_month - 1) DIV 3) + 1)
, v_month
, DATE_FORMAT(v_date, '%M')
, DATE_FORMAT(v_date, '%b')
, DATE_FORMAT(v_date, '%u')
, DATE_FORMAT(v_date, '%d')
, DATE_FORMAT(v_date, '%j')
, DATE_FORMAT(v_date, '%w') + 1
, DATE_FORMAT(v_date, '%W')
, DATE_FORMAT(v_date, '%a')
, IF(DATE_FORMAT(v_date, '%w') IN (0,6), 1, 0)
, IF(DATE_FORMAT(v_date, '%w') IN (0,6), 0, 1)
);
SET v_date := v_date + INTERVAL 1 DAY;
END WHILE;
CALL p_update_dim_date();
END;
//
DROP PROCEDURE IF EXISTS p_update_dim_date;
//
CREATE PROCEDURE p_update_dim_date()
UPDATE dim_date
SET is_today = IF(date_value = current_date, 1, 0)
, is_yesterday = IF(date_value = current_date - INTERVAL 1 DAY, 1, 0)
, is_this_week = IF(year = year(current_date) AND week = DATE_FORMAT(current_date, '%u'), 1, 0)
, is_last_week = IF(year = year(current_date - INTERVAL 7 DAY) AND week = DATE_FORMAT(current_date - INTERVAL 7 DAY, '%u'), 1, 0)
, is_this_month = IF(year = year(current_date) AND month = month(current_date), 1, 0)
, is_last_month = IF(year = year(current_date - INTERVAL 1 MONTH) AND month = month(current_date - INTERVAL 1 MONTH), 1, 0)
, is_this_year = IF(year = year(current_date), 1, 0)
, is_last_year = IF(year = year(current_date - INTERVAL 1 YEAR), 1, 0)
WHERE is_today
OR is_yesterday
OR is_this_week
OR is_last_week
OR is_this_month
OR is_last_month
OR is_this_year
OR is_last_year
OR IF(date_value = current_date, 1, 0)
OR IF(date_value = current_date - INTERVAL 1 DAY, 1, 0)
OR IF(year = year(current_date) AND week = DATE_FORMAT(current_date, '%u'), 1, 0)
OR IF(year = year(current_date - INTERVAL 7 DAY) AND week = DATE_FORMAT(current_date - INTERVAL 7 DAY, '%u'), 1, 0)
OR IF(year = year(current_date) AND month = month(current_date), 1, 0)
OR IF(year = year(current_date - INTERVAL 1 MONTH) AND month = month(current_date - INTERVAL 1 MONTH), 1, 0)
OR IF(year = year(current_date), 1, 0)
OR IF(year = year(current_date - INTERVAL 1 YEAR), 1, 0)
;
//
delimiter ;
Using p_load_dim_date you uinitially load the dim_date table with say 25 years of data. And daily, prefereabluy round midnight, you run p_update_dim_date. Then you can use the flag fields is_today, is_yesterday, is_this_week, is_last_week and so on to select common ranges. Of course, you should amend this code to suit your particular needs but this is the idea. So no generaging ranges on the fly, you just preload for a long enough period of time ahead. For the time of day, a similar design can be set up - you should be able to manage that yourself going by this code.
For even fancier date dimensions that take care of holidays, and localized names for month and days, you can take a look at:
http://rpbouman.blogspot.com/2007/04/kettle-tip-using-java-locales-for-date.html
and
http://rpbouman.blogspot.com/2010/01/easter-eggs-for-mysql-and-kettle.html
I've recently done some research to find and evaluate possible options. http://www.freeportmetrics.com/devblog/2012/11/02/how-to-quickly-add-date-dimension-to-pentaho-mondrian-olap-cube/.
You can use:
kettle
degenerated dimensions
lucidb build-in function
up-coming Mondrian built-in function
your own custom script to generate SQL
mysql script mentioned earlier
Please check the blog post for more details. It also contains improved version of Roland's sql script that will automatically calculate date range for given column and join it with date dimension.
There is no straightforward way to do that in MySQL. Your best bet is to generate a daterange array in your server-side language of choice, and then pull data from the database and merge the resulting array with your daterange array using the date as a key.
Which server side language are you using?
Edit:
Basically what you would do is (pseudocode):
// Create an array with all dates for a given range
dates = makeRange(startDate, endDate);
getData = mysqlQuery('SELECT date, x, y, z FROM a WHERE a AND b AND c');
while (r = fetchRowArray(getData)) {
dates[ date(r['date']) ] = Array ( x, y, z);
}
You end up with an array of dates you can loop through, with the dates that have or don't have activity data associated to them.
Can easily be modified to group / filter data by hours.
Try using a loop in a MySQL stored routine to create date ranges:
declare iterDate date;
set iterDate = startDate;
DROP TABLE IF EXISTS MyDates;
create temporary table MyDates (
theDate date
);
label1: LOOP
insert into MyDates(theDate) values (iterDate);
SET iterDate = DATE_ADD(iterDate, INTERVAL 1 DAY);
IF iterDate <= endDate THEN
ITERATE label1;
END IF;
LEAVE label1;
END LOOP label1;
select * from MyDates;
DROP TABLE IF EXISTS MyDates;
startDate and endDate constitute the endpoints of the range and are supplied as parameters to the routine.
I realise this is an old post but, to keep Stack Overflow a bit up-to-date, I feel the urge to respond.
With the new SEQUENCE engine in MariaDB, this is possible within a SELECT statement without any stored routine or temporary table:
SELECT
DATE_ADD(
CAST('2022-06-01' AS DATE),
INTERVAL `s1`.`seq` DAY
) AS `dates`
FROM `seq_0_to_364` AS `s1`;
Any interval will work as long as it is within the limits of BIGINT(20) UNSIGNED, as this is the limit of the SEQUENCE engine.