SQL query to report duration untill next log entry - sql

I'm working with PostgreSql and trying to build reporting query for my logs, but unfortunately unsuccessfully...
Basically I have LOG table which logs status changes of other entity. So for the sake of simplicity lets say it has columns STATUS and STATUS_CHANGE_DATE. Now each status change updates this logging table with new status and time it was changed. What I need is the duration and number of times status in it for each status (same status can be used multiple times, e.g go from status 1 to 2 then back to 1). I would like to build a view for it and use in my java application reporting by mapping that view right to hibernate entity. Unfortunately I'm not that experienced with sql so maybe someone can give me some hints of whats best solution would be as I tried few things but basically don't know how to do it.
Lets say we have:
STATUS STATUS_CHANGE_DATE
1 2013 01 01
2 2013 01 03
1 2013 01 06
3 2013 01 07
My wanted result would be a table that contains status 1 with 2 times and 3 days duration and status 2 1 time with 3 days duration too (assuming status 3 is end(or close) and its duration is not required).
Any ideas?

if your statuses are changing in every row, you can do this
with cte as (
select
status,
lead(status_change_date) over(order by status_change_date) as next_date,
status_change_date
from Table1
)
select
status, count(*) as cnt,
sum(next_date - status_change_date) as duration
from cte
where next_date is not null
group by status
sql fiddle demo

Try this:
SELECT "STATUS", "STATUS_CHANGE_DATE" - lag("STATUS_CHANGE_DATE") OVER (ORDER BY "STATUS_CHANGE_DATE") AS "DURATION" FROM table ORDER BY "STATUS";
This works for me in a similar case, in my case i need to calculate the average time between sessions in a log table. I hope this works for you.

Related

Create a funnel in SQL with 30 days delay

I have table like this with hundreds of records : month_signup, nb_signups, month_purchase and nb_purchases
month_signup
nb_signups
month_purchase
nb_purchases
01
100
01
10
02
200
02
20
03
150
03
10
Let's say I want to calculate the signup to purchase ratio month after month.
Normaly I can juste divide nb_purchases/nb_signups*100 but here no.
I want to calculate a signup to purchase ratio with 1 month (or 30days) delay.
To let the signups the time to purchase, I want to do the nb_purchase from month 2 divided by nb_signups from month_1. So 20/100 for exemple in my table.
I tried this but really not sure.
SELECT
month_signup
,SAFE_DIVIDE(CASE WHEN purchase_month BETWEEN signups_month AND DATE_ADD(signups_month, INTERVAL 30 DAY) THEN nb_purchases ELSE NULL END, nb_signups)*100 AS sign_up_to_purchase_ratio
FROM table
ORDER BY 1
You can use LEAD() function to get the next value of the current row, I'll provide a MySQL query syntax for this.
with cte as
(select month_signup, nb_signups, lead(nb_purchases) over (order by month_signup) as
nextPr from MyData
order by month_signup)
select cte.month_signup, (nextPr/cte.nb_signups)*100 as per from cte
where (nextPr/cte.nb_signups)*100 is not null;
You may replace (nextPr/cte.nb_signups) with the SAFE_DIVIDE function.
See the demo from db-fiddle.

SQL Query to find out Sequence in next or subsequent rows of a Table based on a condition

I have an SQL Table with following structure
Timestamp(DATETIME)|AuditEvent
---------|----------
T1|Login
T2|LogOff
T3|Login
T4|Execute
T5|LogOff
T6|Login
T7|Login
T8|Report
T9|LogOff
Want the T-SQL way to find out What is the time that the user has logged into the system i.e. Time inbetween Login Time and Logoff Time for each session in a given day.
Day (Date)|UserTime(In Hours) (Logoff Time - LogIn Time)
--------- | -------
Jun 12 | 2
Jun 12 | 3
Jun 13 | 5
I tried using two temporary tables and Row Numbers but could not get it since the comparison was a time i.e. finding out the next Logout event with timestamp is greater than the current row's Login Event.
You need to group the records. I would suggest counting logins or logoffs. Here is one approach to get the time for each "session":
select min(case when auditevent = 'login' then timestamp end) as login_time,
max(timestamp) as logoff_time
from (select t.*,
sum(case when auditevent = 'logoff' then 1 else 0 end) over (order by timestamp desc) as grp
from t
) t
group by grp;
You then have to do whatever you want to get the numbers per day. It is unclear what those counts are.
The subquery does a reverse count. It counts the number of "logoff" records that come on or after each record. For records in the same "session", this count is the same, and suitable for grouping.

Cognos/Flexnet manager SQL - calculate value per time period

I have been tasked with analyzing license utilization via data stored in a database controlled by Flexnet manager (flexlm). What I need to graph is the number of concurrent licenses in use for a specific period of time (high water mark). I am having some trouble doing this as I have very little experience of SQL or BI tools.
I have taken 2 tables, license_events and license_features (these have been filtered for specific users and features). I have then done a join to create a License_feature table. Sample data looks as follows:
CLIENT_PROJECT FEATURE_NAME LIC_COUNT START_TIME EVENT_TIME DURATION
BGTV eclipse 1 1,422,272,438 1422278666 6,228
BGTV eclipse 1 1,422,443,815 1422443845 30
BGTV eclipse 1 1,422,615,676 1422615681 5
BGTV eclipse 1 1,422,631,395 1422631399 4
BGTV eclipse 4 1,422,631,431 1422631434 3
BGTV eclipse 1 1,422,631,465 1422631474 9
BGTV eclipse 1 1,422,631,472 1422631474 2
BGTV eclipse 2 1,422,632,128 1422632147 19
BGTV eclipse 1 1,422,632,166 1422632179 13
BGTV eclipse 6 1,422,632,197 1422632211 14
What I need now is to graph something like this:
For each time (second)
sum(LIC_COUNT) where start_time <= time && end_time >= time
Ideally this should give me the number of concurrent licenses checked out at a specific second. Even better would be if I could get this information for a different time period such as hours or days.
How could I go about doing this?
Use the GROUP BY keywords to group the SUM() together on a specific column. For example, grouping the SUM() of LIC_COUNT by each START_TIME;
SELECT START_TIME, SUM(LIC_COUNT) AS TOTAL_LIC_COUNT
FROM YOUR_TABLE
GROUP BY START_TIME
Now, to SUM() all LIC_COUNT at each increment between START_TIME and END_TIME you'll need to explicitly specify those unique values somewhere else. For example, if you created a table called UniqueTimes that contained all possible values between your earliest START_DATE and last END_DATE. Then you could do something like the following;
SELECT UniqueTime, SUM(LIC_COUNT) AS TotalLicCount
FROM YOUR_TABLE
LEFT JOIN UniqueTimes ON (UniqueTime >= START_TIME AND UniqueTime <= END_TIME)
GROUP BY UniqueTime
This should group your rows as each unique time, and show the total of all summed LIC_COUNT at each specific time.
I hope this helps.

T-Sql Multiple DateDiff with Multiple Start and End Dates Stored in the Same Table?

I'm working on an ERP system that has several workflows for different business processes. In this system I have access to views the vendor provides, not all the underlying tables. There is a log table that records and time stamps every time a record enters and completes one of the workflow steps.
What I want to do is write a query that displays the time in days, to one decimal, how long each record spent in each one of the steps.
In the view I have access to there is no primary key - it looks like this:
Record_id Workflow_id Workflow_Step_id Start_Date Result_Key Complete_Date
Record 1 1422 1 20-Feb-07 9:16:35 PM 7320 23-Mar-07 2:16:10 PM
Record 1 1422 2 23-Mar-07 2:16:10 PM 7320 23-Mar-08 3:13:30 PM
Record 1 1422 3 23-Mar-08 3:13:30 PM 7320 23-Mar-10 8:18:10 AM
Record 1 1422 4 23-Mar-10 8:18:10 AM 7320 23-Mar-13 4:06:57 PM
Essentially the Record_id is what record the time stamp is recording, there are thousands of these and they are not unique because each time a record passes a step in the workflow it gets a new record stamped again.
Workflow_id is simply what workflow the record is going through (i.e. Purchase Order, Engineering Change Request, etc.) - there are multiple workflows so I would need to filter on which workflow is being used for the final results
Workflow_Step_id let's me know what step in the workflow process this times stamp is reflecting.
Result_Key is a numeric way of saying "Passed" or "Rejected" - in this case '7320' means 'Passed' and that's what I'm most interested in (if it matters).
Start_Date and Complete_Date are obvious, but that's what I'm trying to measure the time between, for each step in the Workflow_Step_Id for each record as it goes through the entire workflow.
Ideally this is what my end results would look like, filtered on the proper Workflow_id (1422):
Record_id Step_1 Step_2 Step_3 Step_4
Record 1 30.0 1.0 10.4 3.2
Record 2 10.1 8.2 7.3 4.8
Record 3 2.1 4.1 8.4 6.1
(The math is not exact to the data I provided above, this is just to illustrate what I want the final results to look like.)
You can do this with PIVOT:
;WITH cte AS (SELECT Record_ID, Workflow_Step_ID,CAST(DATEDIFF(hour,Start_Date,Complete_Date)*1.0/24 AS DECIMAL(19,1)) AS Day_Diff
FROM Table1
)
SELECT *
FROM cte
PIVOT(MAX(Day_DIFF) FOR WorkFlow_Step_ID IN ([1],[2],[3],[4]))pvt
Demo: SQL Fiddle
Update: You can use a WHERE clause at the end of the query to split based on your populated [99] field (becomes a field in pivot output, that is:
;WITH cte AS (SELECT Record_ID, Workflow_Step_ID,CAST(DATEDIFF(hour,Start_Date,Complete_Date)*1.0/24 AS DECIMAL(19,1)) AS Day_Diff
FROM Table1
)
SELECT *
FROM cte
PIVOT(MAX(Day_DIFF) FOR WorkFlow_Step_ID IN ([1],[2],[3],[4],[99]))pvt
WHERE [99] IS NULL -- Returns all that weren't terminated, or `IS NOT NULL` for those that are terminated.
Demo: SQL Fiddle
I think you're looking for a pivot table, something along these lines
SELECT Record_id, [1] Step1, [2] Step2, [3] Step3, [4] Step4
FROM (
SELECT Record_id, Workflow_Step_id, cast((Datediff(s, Start_Date, Complete_Date) / 86400.0) as decimal(5, 1)) as DayCnt
FROM tablename t) up
PIVOT (Max(DayCnt) FOR Workflow_Step_id IN ([1], [2], [3], [4])) AS pvt

How do I analyse time periods between records in SQL data without cursors?

The root problem: I have an application which has been running for several months now. Users have been reporting that it's been slowing down over time (so in May it was quicker than it is now). I need to get some evidence to support or refute this claim. I'm not interested in precise numbers (so I don't need to know that a login took 10 seconds), I'm interested in trends - that something which used to take x seconds now takes of the order of y seconds.
The data I have is an audit table which stores a single row each time the user carries out any activity - it includes a primary key, the user id, a date time stamp and an activity code:
create table AuditData (
AuditRecordID int identity(1,1) not null,
DateTimeStamp datetime not null,
DateOnly datetime null,
UserID nvarchar(10) not null,
ActivityCode int not null)
(Notes: DateOnly (datetime) is the DateTimeStamp with the time stripped off to make group by for daily analysis easier - it's effectively duplicate data to make querying faster).
Also for the sake of ease you can assume that the ID is assigned in date time order, that is 1 will always be before 2 which will always be before 3 - if this isn't true I can make it so).
ActivityCode is an integer identifying the activity which took place, for instance 1 might be user logged in, 2 might be user data returned, 3 might be search results returned and so on.
Sample data for those who like that sort of thing...:
1, 01/01/2009 12:39, 01/01/2009, P123, 1
2, 01/01/2009 12:40, 01/01/2009, P123, 2
3, 01/01/2009 12:47, 01/01/2009, P123, 3
4, 01/01/2009 13:01, 01/01/2009, P123, 3
User data is returned (Activity Code 2) immediate after login (Activity Code 1) so this can be used as a rough benchmark of how long the login takes (as I said, I'm interested in trends so as long as I'm measuring the same thing for May as July it doesn't matter so much if this isn't the whole login process - it takes in enough of it to give a rough idea).
(Note: User data can also be returned under other circumstances so it's not a one to one mapping).
So what I'm looking to do is select the average time between login (say ActivityID 1) and the first instance after that for that user on that day of user data being returned (say ActivityID 2).
I can do this by going through the table with a cursor, getting each login instance and then for that doing a select to say get the minimum user data return following it for that user on that day but that's obviously not optimal and is slow as hell.
My question is (finally) - is there a "proper" SQL way of doing this using self joins or similar without using cursors or some similar procedural approach? I can create views and whatever to my hearts content, it doesn't have to be a single select.
I can hack something together but I'd like to make the analysis I'm doing a standard product function so would like it to be right.
SELECT TheDay, AVG(TimeTaken) AvgTimeTaken
FROM (
SELECT
CONVERT(DATE, logins.DateTimeStamp) TheDay
, DATEDIFF(SS, logins.DateTimeStamp,
(SELECT TOP 1 DateTimeStamp
FROM AuditData userinfo
WHERE UserID=logins.UserID
and userinfo.ActivityCode=2
and userinfo.DateTimeStamp > logins.DateTimeStamp )
)TimeTaken
FROM AuditData logins
WHERE
logins.ActivityCode = 1
) LogInTimes
GROUP BY TheDay
This might be dead slow in real world though.
In Oracle this would be a cinch, because of analytic functions. In this case, LAG() makes it easy to find the matching pairs of activity codes 1 and 2 and also to calculate the trend. As you can see, things got worse on 2nd JAN and improved quite a bit on the 3rd (I'm working in seconds rather than minutes).
SQL> select DateOnly
2 , elapsed_time
3 , elapsed_time - lag (elapsed_time) over (order by DateOnly) as trend
4 from
5 (
6 select DateOnly
7 , avg(databack_time - prior_login_time) as elapsed_time
8 from
9 ( select DateOnly
10 , databack_time
11 , ActivityCode
12 , lag(login_time) over (order by DateOnly,UserID, AuditRecordID, ActivityCode) as prior_login_time
13 from
14 (
15 select a1.AuditRecordID
16 , a1.DateOnly
17 , a1.UserID
18 , a1.ActivityCode
19 , to_number(to_char(a1.DateTimeStamp, 'SSSSS')) as login_time
20 , 0 as databack_time
21 from AuditData a1
22 where a1.ActivityCode = 1
23 union all
24 select a2.AuditRecordID
25 , a2.DateOnly
26 , a2.UserID
27 , a2.ActivityCode
28 , 0 as login_time
29 , to_number(to_char(a2.DateTimeStamp, 'SSSSS')) as databack_time
30 from AuditData a2
31 where a2.ActivityCode = 2
32 )
33 )
34 where ActivityCode = 2
35 group by DateOnly
36 )
37 /
DATEONLY ELAPSED_TIME TREND
--------- ------------ ----------
01-JAN-09 120
02-JAN-09 600 480
03-JAN-09 150 -450
SQL>
Like I said in my comment I guess you're working in MSSQL. I don't know whether that product has any equivalent of LAG().
If the assumptions are that:
Users will perform various tasks in no mandated order, and
That the difference between any two activities reflects the time it takes for the first of those two activities to execute,
Then why not create a table with two timestamps, the first column containing the activity start time, the second column containing the next activity start time. Thus the difference between these two will always be total time of the first activity. So for the logout activity, you would just have NULL for the second column.
So it would be kind of weird and interesting, for each activity (other than logging in and logging out), the time stamp would be recorded in two different rows--once for the last activity (as the time "completed") and again in a new row (as time started). You would end up with a jacob's ladder of sorts, but finding the data you are after would be much more simple.
In fact, to get really wacky, you could have each row have the time that the user started activity A and the activity code, and the time started activity B and the time stamp (which, as mentioned above, gets put down again for the following row). This way each row will tell you the exact difference in time for any two activities.
Otherwise, you're stuck with a query that says something like
SELECT TIME_IN_SEC(row2-timestamp) - TIME_IN_SEC(row1-timestamp)
which would be pretty slow, as you have already suggested. By swallowing the redundancy, you end up just querying the difference between the two columns. You probably would have less need of knowing the user info as well, since you'd know that any row shows both activity codes, thus you can just query the average for all users on any given day and compare it to the next day (unless you are trying to find out which users are having the problem as well).
This is the faster query to find out, in one row you will have current and row before datetime value, after that you can use DATEDIFF ( datepart , startdate , enddate ). I use #DammyVariable and DamyField as i remember the is some problem if is not first #variable=Field in update statement.
SELECT *, Cast(NULL AS DateTime) LastRowDateTime, Cast(NULL As INT) DamyField INTO #T FROM AuditData
GO
CREATE CLUSTERED INDEX IX_T ON #T (AuditRecordID)
GO
DECLARE #LastRowDateTime DateTime
DECLARE #DammyVariable INT
SET #LastRowDateTime = NULL
SET #DammyVariable = 1
UPDATE #T SET
#DammyVariable = DammyField = #DammyVariable
, LastRowDateTime = #LastRowDateTime
, #LastRowDateTime = DateTimeStamp
option (maxdop 1)