Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How do I calculate time these two blocks Start and Submit?
The Activity column has Start and Submit. I need to calculate the time difference between Submit and the Start before the Submit Activity. How do we calculate that?
Thanks!
Here is the sample Table:
Sample Table
I took the liberty of converting your image to a usable table:
DECLARE #Activity TABLE (Activity VARCHAR(MAX), Timestamp DATETIME)
INSERT #Activity
VALUES
('Start', '5/12/21 3:30 PM'),
('Start', '5/13/21 3:31 PM'),
('Start', '5/14/21 3:33 PM'),
('Submit', '5/15/21 3:36 PM'),
('Start', '5/14/21 3:37 PM')
Without any other identifier to associate the start and submit times, I will assume that the most recent Start applies to a Submit and that other Start entries are ignored. For any given Submit, one way to select a candidate Start is with a CROSS APPLY and appropriate selection, ordering, and TOP 1 criteria. Something like:
SELECT
StartTime = ST.TimeStamp,
SubmitTime = SU.TimeStamp,
Elapsed = SU.TimeStamp - ST.TimeStamp,
ElapsedMinutes = DATEDIFF(minute, ST.TimeStamp, SU.TimeStamp)
FROM #Activity SU
CROSS APPLY (
SELECT TOP 1 *
FROM #Activity ST
WHERE ST.Activity = 'Start'
AND ST.TimeStamp <= SU.TimeStamp
ORDER BY ST.TimeStamp DESC
) ST
WHERE SU.Activity = 'Submit'
Note the last record of your data is the actual closest match using the above criteria, yielding 1439 minutes of elapsed time. If your table contains keys that better associate your start and submit times, you should adjust the above logic accordingly.
I would also recommend an index on TimeStamp for efficient lookup.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am practicing on a database on SQL server where the date column in the table is Nvarchar(255) thereby presenting the dates as five digit numbers eg 40542,40046 etc. How do I change the dates in the column to actual dates?
The articles I checked only helped me to change rows but I can't change all of them individually as that will take time.
If dates from Excel, this is to expand on my comment.
Here are two approaches
Example
Declare #YourTable Table ([SomeCol] nvarchar(255)) Insert Into #YourTable Values
('40542')
,('40043')
Select *
,AsDate1 = try_convert(datetime,try_convert(float,SomeCol)-2.0)
,AsDate2 = dateadd(day,try_convert(int,SomeCol),'1899-12-30') -- Note Start Date
From #YourTable
Results
SomeCol AsDate1 AsDate2
40542 2010-12-30 2010-12-30
40043 2009-08-18 2009-08-18
You have a strange database. Basically, you want
UPDATE TableName
SET NewDateColName = ConvertionFunction(OldDateColName)
But more info is needed on how to convert the 5 digit number encoded as a string, into a date.
CAST(OldDateColName as Date)
Might work, or you may have to apply some arithmetics after casting to int.
For excel dates:
UPDATE TableName
SET NewDateColName = CONVERT(numeric(18,4),OldDateColName,101)
The values of your "dates" suggests that your dates reflect an offset in days since the epoch (zero point on the calendar system) of 1 January 1900.
For instance, the values you cited are:
40452: Sunday, October 3, 2010
40046: Sunday, August 23, 2009
In which case you should be able to say something like
create view dbo.my_improved_view
as
select t.* ,
some_date = date_add( day,
convert( int , t.funky_date_column ),
convert( date , '1900-01-01' )
)
from dbo.table_with_funky_date_column t
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to build a SQL query in which I can get time spent on multiple statuses (onHold,Waiting for customer,Resolved,Closed), so basically I do not want to include time spent on this statues and table looks like as below
So I need a query in which I can get actual time spent on ticket or time spent on status which I have mentioned so far I have tried below solutions and tried Cross APPLY but seems all did not help me as expected.
Tried below query so far and that gives me correct time spent on first status on-hold not after that:
SELECT t1.TICKETNUMBER,SUM(DATEDIFF(MINUTE,TICKETTIME,CloseTime)) as TotalMinutes
FROM [Admin].[TbtrnTicketHistory] t1
CROSS APPLY(SELECT TOP 1 TICKETTIME as CloseTime FROM [Admin].[TbtrnTicketHistory] t2 WHERE t1.TICKETNUMBER = t2.TICKETNUMBER and t2.TICKETHISTORYID > t1.TICKETHISTORYID ORDER BY t2.TICKETTIME) as t2
WHERE t1.CURRENTSTATUS_ANALYST not in('On-Hold','Waiting For Customer','Resolved','Closed') and t1.ticketnumber = '211135'
GROUP BY t1.TICKETNUMBER;
calculate difference between two times in two rows in sql
Calculate Time Difference Between Two Consecutive Rows
with SQL Server you can use those very usefull windowed functions LEAD and FIRST_VALUE :
select *
,[duration(sec)] = DATEDIFF(SECOND
,ticketTime
,LEAD(ticketTime,1,ticketTime)over(partition by ticketNumber order by ticketTime)
)
,[cumulative duration(sec)] = DATEDIFF( SECOND
, FIRST_VALUE(ticketTime)over(partition by ticketNumber order by ticketTime)
, ticketTime)
from (values
(1,cast('20211101 10:00:01' as datetime))
,(1,'20211101 10:00:33')
,(1,'20211101 10:01:59')
)T(ticketNumber,ticketTime)
ticketNumber
ticketTime
duration(sec)
cumulative duration(sec)
1
2021-11-01 10:00:01.000
32
0
1
2021-11-01 10:00:33.000
86
32
1
2021-11-01 10:01:59.000
0
118
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In my table, I have a field RAZ (bit) whose value is 0 except at 5am, 1pm and 9pm when it's equal to 1. I would like to get the last rows in my table before RAZ is equal to 1.
Here is a sample data :
For exemple, the final request would display the row with idEvenement = 8454.
I will use this request in a stored procedure to compute indicators.
The RAZ field changes to 1 automatically, it means that the data has been reset.
I don't know if it's possible and how to do it.
You can use SQL Server windowing function LEAD to see if the next record's RAZ turns to 1 while it was 0 before. LEAD gets the next record based on RAZTime order. This returns ID = 8454 as the result
; WITH cte (ID, RAZTime, RAZ) AS (
SELECT 8456, convert(datetime, '13:01 pm'), 1
union SELECT 8455, convert(datetime, '13:00 pm'), 1
union SELECT 8454, convert(datetime, '12:59 pm'), 0
union SELECT 8453, convert(datetime, '12:58 pm'), 0
)
, q AS (
SELECT
*
, NextRAZ = LEAD (RAZ, 1, NULL) OVER (ORDER BY RAZTime)
FROM cte
)
SELECT *
FROM q
WHERE
RAZ = 0
AND NextRAZ = 1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a query like below and I want to make calculation for end_scan-packing_date column, how can I achieve this?
SELECT a.invoice_no,
CONVERT(VARCHAR, b.packing_date,3) as packing_date ,
CONVERT(VARCHAR, b.exw_date,3) as exw,
CONVERT(VARCHAR, b.bcd_end_date, 3) as end_date,
(SELECT TOP 1 insert_date FROM wms.bcd_shipment d,wms.shinvoicedetails WHERE d.invoice_no = a.invoice_no ORDER BY insert_date ASC) as start_date ,
(SELECT TOP 1 insert_date FROM wms.bcd_shipment d,wms.shinvoicedetails WHERE d.invoice_no = a.invoice_no ORDER BY insert_date DESC) as end_scan,
CONVERT(VARCHAR, send_date, 3) as swnd_date,customer_short_name,
Sum(picking_qty) as qty,total_carton
FROM wms.shinvoicedetails a,
wms.shinvoiceheder b,
wms.shinvoice_ctrl c
WHERE send_date BETWEEN '2014/8/26 00:00:01' AND '2014/9/25 23:59:59'
AND a.invoice_no = b.invoice_no
AND a.invoice_no = c.invoice_no
GROUP BY a.invoice_no,
b.packing_date,
b.exw_date,
b.bcd_end_date,
send_date,
customer_short_name,
total_carton
ORDER BY 1;
May I refer you to the documentation for the DATEDIFF function (I'm assuming your're using SQL Server as RDBMS).
It has 3 parameters, I am assuming you want the difference in days. So what you want would read something like:
DATEDIFF(DAY,
(SELECT TOP 1 insert_date
FROM wms.bcd_shipment d,
wms.shinvoicedetails
WHERE d.invoice_no = a.invoice_no
ORDER BY insert_date DESC),
b.packing_date
) AS diff_days
Your query is wrong on many levels though. You are grouping on nearly all columns to get a SUM while you should write that as a derived table (a sub-query) grouping only on the necessary fields. Also you are converting to VARCHAR which probably translates to VARCHAR(1). You should probably write it as CONVERT(VARCHAR(10), <your date field>, 3).
A day does not start at 00:00:01 and does not finish as 23:59:59. Do yourself a favour an don't try to bend your needs to the syntax of between. There is an easier and more reliable method
WHERE send_date >= '20140826' AND send_date < '20140926'
LESS THAN the 26th; it's more accurate & no silly one second deductions.
the best practice with date and time ranges is to avoid BETWEEN and to
always use the form:
WHERE col >= '20120101' AND col < '20120201'
This form works with all
types and all precisions, regardless of whether the time part is
applicable.
Itzik Ben-Gan
http://sqlmag.com/t-sql/t-sql-best-practices-part-2
This question already has answers here:
TSQL to combine a date field and a time field
(4 answers)
Closed 9 years ago.
I have a database that stores date and time in separate fields. I need to select all records that occurred within + and - 90 minutes of the date and time each of these happened.
I am able to get everything in the format I need to pull it off
SELECT UFV1.USR_DATE
,UFV1.USR_TIME
,LEFT(CAST(DATEADD(minute, -90, UFV1.USR_TIME) AS TIME),8) AS MIN_TIME
,LEFT(CAST(DATEADD(minute, +90, UFV1.USR_TIME) AS TIME),8)AS MAX_TIME
FROM USR_Y_FACILITY_VISIT UFV1
WHERE UFV1.MASTER_CUSTOMER_ID = '2'
ORDER BY UFV1.USR_DATE, UFV1.USR_TIME
Where I am stuck is I need to build a query that takes this info (basically the min/max from each line) then selects all the info in the same table based off that. Thank you for your help I am totally stumped as to where to go next.
Add the key fields for the table to your query as given, along with a corresponding GROUP BY clause. Then query your data table joind to that query as a sun-query on this format:
SELECT *
FROM T
JOIN ( SELECT * ... ) U
ON U.key = T.key
AND T.dateTime BETWEENU.MinDateTime AND U.MaxDateTime
If I correctly understood a question then, this request is necessary for you
SELECT *
FROM USR_Y_FACILITY_VISIT UFV1
WHERE EXISTS (
SELECT 1
FROM USR_Y_FACILITY_VISIT UFV2
WHERE UFV2.MASTER_CUSTOMER_ID = '2'
AND UFV1.USR_DATE = UFV2.USR_DATE
AND UFV1.USR_TIME BETWEEN CAST(DATEADD(minute, -90, UFV2.USR_TIME) AS time)
AND CAST(DATEADD(minute, 90, UFV2.USR_TIME) AS time)
)