A trigger to calculate hour difference between two DateTime fields - sqlite

3 fields in a Table : START_DATE, END_DATE , DIFF. All three are DATETIME fields. I would like a trigger (AFTER UPDATE) to calculate the time difference between the START_DATE and END_DATE values in the DIFF field. I would like the result to be like : 01 Day - 12 Hours - 15 Min. How can I achieve this ? I would like to know also how it is done i.e the way to show the hour difference so that DIFF would display something like 27:15:00.
This seems to work:
CREATE TRIGGER [DIFF]
AFTER UPDATE OF [end_date]
ON [Table1]
BEGIN
UPDATE Table1 SET DIFF =
cast(
(
strftime('%s',Table1.end_date)-strftime('%s',Table1.start_date)
) AS INT
) / 60/60 ;
END

As far as I can tell, this works ok:
CREATE TRIGGER [TIME_DIFFERENCE]
AFTER UPDATE OF [end_date]
ON [Table1]
BEGIN
UPDATE Table1 SET DIFF =
cast(
(
strftime('%s',Table1.end_date)-strftime('%s',Table1.start_date)
) AS INT
) / 60/60 ;
END

Related

Impala - Working hours between two dates in impala

I have two time stamps #starttimestamp and #endtimestamp. How to calculate number of working hours between these two
Working hours is defined below:
Mon- Thursday (9:00-17:00)
Friday (9:00-13:00)
Have to work in impala
think i found a better solution.
we will create a series of numbers using a large table. You can get a time dimension type table too. Make it doenst get truncated. I am using a large table from my db.
Use this series to generate a date range between start and end date.
date_add (t.start_date,rs.uniqueid) -- create range of dates
join (select row_number() over ( order by mycol) as uniqueid -- create range of unique ids
from largetab) rs
where end_date >=date_add (t.start_date,rs.uniqueid)
Then we will calculate total hour difference between the timestamp using unix timestamp considering date and time.
unix_timestamp(endtimestamp - starttimestamp )
Exclude non working hours like 16hours on M-T, 20hours on F, 24hours on S-S.
case when dayofweek ( dday) in (1,7) then 24
when dayofweek ( dday) =5 then 20
else 16 end as non work hours
Here is complete SQL.
select
end_date, start_date,
diff_in_hr - sum(case when dayofweek ( dday) in (1,7) then 24
when dayofweek ( dday) =5 then 20
else 16 end ) total_workhrs
from (
select (unix_timestamp(end_date)- unix_timestamp(start_date))/3600 as diff_in_hr , end_date, start_date,date_add (t.start_date,rs.uniqueid) as dDay
from tdate t
join (select row_number() over ( order by mycol) as uniqueid from largetab) rs
where end_date >=date_add (t.start_date,rs.uniqueid)
)rs2
group by 1,2,diff_in_hr

SQL: Sum based on specified dates

Thanks again for the help everyone. I went with the script below...
SELECT beginning, end,
(SELECT SUM(sale) FROM sales_log WHERE date BETWEEN beginning AND `end` ) AS sales
FROM performance
and I added a salesperson column to both the performance table and sales_log but it winds up crashing DB Browser. What is the issue here? New code below:
SELECT beginning, end, salesperson
(SELECT SUM(sale) FROM sales_log WHERE (date BETWEEN beginning AND end) AND sales_log.salesperson = performance.salesperson ) AS sales
FROM performance
I believe that the following may do what you wish or be the basis for what you wish.
WITH sales_log_cte AS
(
SELECT substr(date,(length(date) -3),4)||'-'||
CASE WHEN length(replace(substr(date,instr(date,'/')+1,2),'/','')) < 2 THEN '0' ELSE '' END
||replace(substr(date,instr(date,'/')+1,2),'/','')||'-'||
CASE WHEN length(substr(date,1,instr(date,'/') -1)) < 2 THEN '0' ELSE '' END||substr(date,1,instr(date,'/') -1) AS date,
CAST(sale AS REAL) AS sale
FROM sales_log
),
performance_cte AS
(
SELECT substr(beginning,(length(beginning) -3),4)||'-'||
CASE WHEN length(replace(substr(beginning,instr(beginning,'/')+1,2),'/','')) < 2 THEN '0' ELSE '' END
||replace(substr(beginning,instr(beginning,'/')+1,2),'/','')||'-'||
CASE WHEN length(substr(beginning,1,instr(beginning,'/') -1)) < 2 THEN '0' ELSE '' END||substr(beginning,1,instr(beginning,'/') -1)
AS beginning,
substr(`end`,(length(`end`) -3),4)||'-'||
CASE WHEN length(replace(substr(`end`,instr(`end`,'/')+1,2),'/','')) < 2 THEN '0' ELSE '' END
||replace(substr(`end`,instr(`end`,'/')+1,2),'/','')||'-'||
CASE WHEN length(substr(`end`,1,instr(`end`,'/') -1)) < 2 THEN '0' ELSE '' END||substr(`end`,1,instr(`end`,'/') -1)
AS `end`
FROM performance
)
SELECT beginning, `end` , (SELECT SUM(sale) FROM sales_log_cte WHERE date BETWEEN beginning AND `end` ) AS sales
FROM performance_cte
;
From your data this results in :-
As can be seen the bulk of the code is converting the dates into a format (i.e. YYYY-MM-DD) that is usable/recognisable by SQLite for the BETWEEN clause.
Date And Time Functions
I don't believe that you want a join between performance (preformance_cte after reformatting the dates) and sales_log (sales_log_cte) as this will be a cartesian product and then sum will sum all the results within the range.
The use of end as a column name is also awkward as it is a KEYWORD requiring it to be enclosed (` grave accents used in the above).
The above works by using 2 CTE's (Common Table Expresssions), which are temporary tables who'd life time is for the query in which they are used.
The first sales_log_cte is simply the sales_log table but with the date reformatted. The second, likewise, is simply the performace table with the dates reformatted.
If the tables already has suitable date formatting then all of the above could simply be :-
SELECT beginning, `end` , (SELECT SUM(sale) FROM sales_log WHERE date BETWEEN beginning AND `end` ) AS sales FROM performance;

Select weekend or weekday data from a table based on date param

How can I select data from a table based on weekday or weekend, like
if date is a weekday then select only historical weekday data from the table &
if date is a weekend then select only historical weekend data.
I have tried to do that in this way but no luck
DECLARE #MyDate DATE = '08/17/2013'
SELECT datename(dw,#MyDate)
SELECT * FROM MyTable
WHERE
datename(dw,DateColumnInTable) IN (
CASE WHEN (datename(dw,#MyDate) IN ('Saturday','Sunday')) THEN '''Saturday'',''Sunday'''
ELSE 'Monday'',''Tuesday'',''Wednesday'',''Thursday'',''Friday'
END )
Any I can see lots of data in my table for saturday and sunday but this query is giving me blank record set.
Here's one way:
DECLARE #MyDate DATE = '08/17/2013'
IF (DATEPART(weekday, #MyDate) IN (1,7))
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) IN (1,7)
ELSE
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6
If you would like to do it in one clause you can do something like the following, but it may perform worse:
SELECT *
FROM MyTable
WHERE (DATEPART(weekday, #MyDate) IN (1,7) AND DATEPART(weekday, DateColumnInTable) IN (1,7))
OR (DATEPART(weekday, #MyDate) BETWEEN 2 AND 6 AND DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6)

I need to calculate the date / time difference between one date time column

Details.
I have the notes table having the following columns.
ID - INT(3)
Date - DateTime
Note - VARCHAR(100)
Tile - Varchar(100)
UserName - Varchar(100)
Now this table will be having NOTES along with the Titles entered by UserName on the specified date / time.
I need to calculate the DateTimeDifference between the TWO ROWS in the SAME COLUMN
For example the above table has this peice of information in the table.
64, '2010-03-26 18:16:13', 'Action History', 'sending to Level 2.', 'Salman Khwaja'
65, '2010-03-26 18:19:48', 'Assigned By', 'This is note one for the assignment of RF.', 'Salman Khwaja'
66, '2010-03-27 19:19:48', 'Assigned By', 'This is note one for the assignment of CRF.', 'Salman Khwaja'
Now I need to have the following resultset in query reports using MYSQL.
TASK - TIME Taken
ACTION History - 2010-03-26 18:16:13
Assigned By - 00:03:35
Assigned By - 25:00:00
More smarter approach would be
TASK - TIME Taken
ACTION History - 2010-03-26 18:16:13
Assigned By - 3 minutes 35 seconds
Assigned By - 1 day, 1 hour.
I would appreciate if one could give me the PLAIN QUERY along with PHP code to embed it too.
<?php
$start = new DateTime('2009-01-01 00:00:00'); // 31 days
$time_span = $start->diff(new DateTime('2009-02-01 00:00:00'));
var_dump($time_span); // returns '1 month'
$start = new DateTime('2009-02-01 00:00:00'); //28 days
$time_span = $start->diff(new DateTime('2009-03-01 00:00:01'));
var_dump($time_span); // returns '1 month'
?>
DATEDIFF()
It looks like you want to group by case number.
Using your schema and sample data, I think that this is exactly what you wanted:
SELECT t1.ID, t1.title AS task, t1.username,
IFNULL(CONCAT(TIMESTAMPDIFF(MINUTE, t2.currentDate, t1.currentDate)), t1.currentdate) AS time_taken
FROM tps_trans_support_notes t1
LEFT JOIN tps_trans_support_notes t2
ON t2.currentdate < t1.currentdate AND
t2.ID <> t1.ID AND
t2.casenumber = t1.casenumber
LEFT JOIN tps_trans_support_notes t3
ON t3.casenumber = t1.casenumber AND
t3.ID <> t1.ID AND t3.ID <> t2.ID AND
t3.currentdate > t2.currentdate AND
t3.currentdate < t1.currentdate
WHERE t3.ID IS NULL AND
t1.casenumber = '21'
ORDER BY t1.ID
First, the query gets the begin time and end time into the same row, excluding rows where there are times that occur between the two, then it displays the difference.
The query only shows the difference in minutes, but you can use the other DateTime functions to expand that.

Sum amount of overlapping datetime ranges in MySQL

I have a table of events, each with a StartTime and EndTime (as type DateTime) in a MySQL Table.
I'm trying to output the sum of overlapping times and the number of events that overlapped.
What is the most efficient / simple way to perform this query in MySQL?
CREATE TABLE IF NOT EXISTS `events` (
`EventID` int(10) unsigned NOT NULL auto_increment,
`StartTime` datetime NOT NULL,
`EndTime` datetime default NULL,
PRIMARY KEY (`EventID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;
INSERT INTO `events` (`EventID`, `StartTime`, `EndTime`) VALUES
(10001, '2009-02-09 03:00:00', '2009-02-09 10:00:00'),
(10002, '2009-02-09 05:00:00', '2009-02-09 09:00:00'),
(10003, '2009-02-09 07:00:00', '2009-02-09 09:00:00');
# if the query was run using the data above,
# the table below would be the desired output
# Number of Overlapped Events | Total Amount of Time those events overlapped.
1, 03:00:00
2, 02:00:00
3, 02:00:00
The purpose of these results is to generate a bill for hours used. (if you have one event running, you might pay 10 dollars per hour. But if two events are running, you only have to pay 8 dollars per hour, but only for the period of time you had two events running.)
Try this:
SELECT `COUNT`, SEC_TO_TIME(SUM(Duration))
FROM (
SELECT
COUNT(*) AS `Count`,
UNIX_TIMESTAMP(Times2.Time) - UNIX_TIMESTAMP(Times1.Time) AS Duration
FROM (
SELECT #rownum1 := #rownum1 + 1 AS rownum, `Time`
FROM (
SELECT DISTINCT(StartTime) AS `Time` FROM events
UNION
SELECT DISTINCT(EndTime) AS `Time` FROM events
) AS AllTimes, (SELECT #rownum1 := 0) AS Rownum
ORDER BY `Time` DESC
) As Times1
JOIN (
SELECT #rownum2 := #rownum2 + 1 AS rownum, `Time`
FROM (
SELECT DISTINCT(StartTime) AS `Time` FROM events
UNION
SELECT DISTINCT(EndTime) AS `Time` FROM events
) AS AllTimes, (SELECT #rownum2 := 0) AS Rownum
ORDER BY `Time` DESC
) As Times2
ON Times1.rownum = Times2.rownum + 1
JOIN events ON Times1.Time >= events.StartTime AND Times2.Time <= events.EndTime
GROUP BY Times1.rownum
) Totals
GROUP BY `Count`
Result:
1, 03:00:00
2, 02:00:00
3, 02:00:00
If this doesn't do what you want, or you want some explanation, please let me know. It could be made faster by storing the repeated subquery AllTimes in a temporary table, but hopefully it runs fast enough as it is.
Start with a table that contains a single datetime field as its primary key, and populate that table with every time value you're interested in. A leap years has 527040 minutes (31622400 seconds), so this table might get big if your events span several years.
Now join against this table doing something like
SELECT i.dt as instant, count(*) as events
FROM instant i JOIN event e ON i.dt BETWEEN e.start AND e.end
GROUP BY i.dt
WHERE i.dt BETWEEN ? AND ?
Having an index on instant.dt may let you forgo an ORDER BY.
If events are added infrequently, this may be something you want to precalculate by running the query offline, populating a separate table.
I would suggest an in-memory structure that has start-time,end-time,#events... (This is simplified as time(hours), but using unix time gives up to the second accuracy)
For every event, you would insert the new event as-is if there's no overlap, otherwise, find the overlap, and split the event to (up to 3) parts that may be overlapping, With your example data, starting from the first event:
Event 1 starts at 3am and ends at 10am: Just add the event since no overlaps:
3,10,1
Event 2 starts at 5am and ends at 9am: Overlaps,so split the original, and add the new one with extra "#events"
3,5,1
5,9,2
9,10,1
Event 3 starts at 7am and ends at 9am: also overlaps, do the same with all periods:
3,5,1
5,7,2
7,9,3
9,10,1
So calculating the overlap hours per #events:
1 event= (5-3)+(10-9)=3 hours
2 events = 7-5 = 2 hours
3 events = 9-7 = 2 hours
It would make sense to run this as a background process if there are many events to compare.

Resources