I apologize if the title is not clear enough but is this possible to do in Qlikview?
This is the original table loaded from database.
Variable Status Date Duration (Hours)
A StatusA 9/10/2017 18:30:00.00 4
A StatusB 9/10/2017 23:30:00.00 5
B StatusA 9/10/2017 10:00:00.00 8
B StatusB 9/10/2017 21:45:00.00 9
And how I want this to process.
Variable Status Date Duration (Hours) FinishDate
A StatusA 9/10/2017 18:30:00.00 4 9/10/2017 22:30:00.00
A StatusB 9/10/2017 23:30:00.00 0.5 9/10/2017 23:59:59.59
A StatusB 9/11/2017 0:00:00.00 4.5 9/11/2017 3:30:00.00
B StatusA 9/10/2017 10:00:00.00 8 9/10/2017 18:00:00.00
B StatusB 9/10/2017 21:45:00.00 2.25 9/10/2017 23:59:59.59
B StatusB 9/11/2017 0:00:00.00 6.75 9/11/2017 6:15:00.00
I know this is possible through resident table but how to check if the Variable's running time exceeded a day then creates another row to separate the duration to next day. This is the case because I have a filter by week so if the last day (or Saturday) has a Variable with exceeded duration, data won't be accurate.
The result data will need to get the total duration per Variable which is filtered by week.
Script:
T1:
LOAD *, timestamp(Timestamp+[Duration Hours]/24) as FinishDate;
LOAD *, timestamp(Timestamp#(left(Date,19),'DD-MM-YYYY hh:mm:ss')) as Timestamp;
LOAD
[EquipmentID] AS [Equipment ID],
[TransactionDate] AS [Date],
[LotID] AS [Lot ID],
[Status] AS [Status],
[DurationHours] AS [Duration Hours];
SQL
SELECT *
FROM [SQL_SourceDB].[dbo].[SourceTable]
WHERE [TransactionDate] >= '2016-01-01 00:00:00.000' AND [TransactionDate] <= '2016-01-31 00:00:00.000';
Left Join // add a split-flag where needed
LOAD Distinct Timestamp,FinishDate,fabs(Date(left(FinishDate,10))-Date(left(Timestamp,10)) >=1) as SplitFlag
Resident T1;
T2: // load first part (current day) of split-flag=1
LOAD
[Equipment ID],
[Timestamp] AS [Date],
[Lot ID],
[Status],
round((DayEnd(Timestamp)-Timestamp)*24,0.1) AS [Duration Hours]
Resident T1
Where SplitFlag=1;
Concatenate // load second part (next day) where split-flag=1
LOAD
[Equipment ID],
daystart(FinishDate) AS [Date],
[Lot ID],
[Status],
round((FinishDate-daystart(FinishDate))*24,0.1) AS [Duration Hours]
Resident T1
Where SplitFlag=1;
Concatenate // add the rest of the data (split-flag=0)
LOAD * Resident T1 Where SplitFlag=0;
DROP Table T1;
This should work (see comments in code):
T1: // first need to set a proper timestamp and FinishDate
Load *, timestamp(Timestamp+[Duration (Hours)]/24) as FinishDate;
Load *, timestamp(Timestamp#(left(Date,19),'DD-MM-YYYY hh:mm:ss')) as Timestamp;
LOAD * INLINE [
Variable, Status, Date, Duration (Hours)
A, StatusA, 10-09-2017 18:30:00.00, 4
A, StatusB, 10-09-2017 23:30:00.00, 5
B, StatusA, 10-09-2017 10:00:00.00, 8
B, StatusB, 10-09-2017 21:45:00.00, 9
];
left join // add a split-flag where needed
Load Distinct Timestamp,FinishDate,fabs(Date(left(FinishDate,10))-Date(left(Timestamp,10)) >=1) as SplitFlag
Resident T1;
T2: // load first part (current day) of split-flag=1
Load Variable,Status,
Timestamp,
dayEnd(Timestamp) as FinishDate,
round((DayEnd(Timestamp)-Timestamp)*24,0.1) as [Duration (Hours)]
Resident T1
where SplitFlag=1;
Concatenate // load second part (next day) where split-flag=1
Load Variable,Status,
daystart(FinishDate) as Timestamp,
FinishDate,
round((FinishDate-daystart(FinishDate))*24,0.1) as [Duration (Hours)]
Resident T1
where SplitFlag=1;
Concatenate // add the rest of the data (split-flag=0)
Load * Resident T1 Where SplitFlag=0;
drop table T1;
Related
I would like to ask a little help on using dynamic sql date header,
i have data that i count transaction group by date then by hours.
date range would be entered start date and end date.
my data is simple just date and time:
created_Date
'2020-01-14 13:25:20.147'
'2020-01-14 13:23:15.639'
'2020-01-14 12:27:48.896'
'2020-01-09 20:03:06.713'
'2020-01-09 19:33:05.032'
'2020-01-09 19:16:35.590'
'2020-01-09 19:08:19.788'
'2020-01-09 13:02:03.543'
'2020-01-09 12:23:12.595'
'2020-01-08 15:29:52.262'
'2020-01-08 15:17:31.247'
'2020-01-08 15:16:51.499'
'2020-01-08 13:29:47.661'
'2020-01-06 20:19:30.173'
currently found this code:
ALTER PROCEDURE "DBA"."test_trancountdaily"(#sdate datetime, #edate datetime)
BEGIN
create table #trantable(TDate varchar(100),Hour varchar(2), count varchar(1000));
insert #trantable
SELECT CAST(created_date as date) AS ForDate,
DATEPART(hour,created_date) AS OnHour,
COUNT(*) AS Totals
FROM prescription
WHERE created_date >= #sdate and created_date <= #edate
GROUP BY CAST(created_date as date),
DATEPART(hour,created_date)
ORDER BY CAST(created_date as date),
DATEPART(hour,created_date) asc;
select * from #trantable;
END
my data are created_date datetime and would count how many transaction that is inside a Hour
but would like an output like this:
HR
2020-01-01
2020-01-02
2020-01-03 etc
1
1
0
3
2
0
1
1
3
1
1
1
4
1
0
2
thanks
bolivar1985
Sample Result in interactive sql
Good Day,
Just solve query without using pivot in sybase it was mind troubling but got it.
set #sql_date = #sql_date + ', COUNT(CASE WHEN DATE(prescription.created_date) = ''' + #ls_date +
''' AND #time_table.hrs = HOUR(prescription.created_date) THEN prescription.tran_id END) AS
[' + #ls_date + ']' ;
looping the date range to be given by user, and date as header.
bolivar1985
I have 3 table t1, t2 and t3.
t1 has 2 column-> id1, val1
t2 -> id2, val2
t3 -> id3, val3
If id1=id2 and id2 = id3
then I need to update val1 ad val3.
But I have repeating id1 and each should have same val3
I am using
update t1
inner join t2 on t1.id1 = t2.id2
inner join t3 on t2.id2 = t3.id3
set t1.val1 = t3.val3
;
But not able to do this.
The correct syntax is:
UPDATE table_name SET column = { expression | DEFAULT } [,...]
[ FROM fromlist ]
[ WHERE condition ]
So your UPDATE statement should look as follows:
update t1 set val1 = val3
from t2 inner join t3 on t2.id2 = t3.id3
where t1.id1 = t2.id2
;
See the Redshift documentation and their comprehensive UPDATE examples.
I needed to get values from the other table, t2.val3, on Redshift. I used the following
update t1
set val1 = t2.val3
from t2 join t1 t on t.id = t2.id;
I have to re-name t1. Otherwise Redshift complains.
Per #jie solution, but expanded a bit and w/o the distraction of a table alias as a table name (heh heh):
update
my_counts
set
my_count_delta = t1.my_count - t2.my_count
from
my_counts t1 join
my_counts t2 on
t1.group_id = t2.group_id and
t2.count_dt = ( t1.count_dt - interval '1 day' )
where
t1.count_error is null
A few notes:
my_count is a running total
my_count_delta is the change from the previous day entry (-/+)
this solves the issue where running total exists, but summarial columnar data for the delta needs to be added
:heart: how pg style sql makes date add/subtraction so simple: ( t1.count_dt - interval '1 day' )
as an avid lover of LEFT JOIN i was confounded that this would not run with a left join...the error message was very clear requiring "balanced join" or was it "even join"...so i went back to the #jie version of JOIN and found that the query was incredibly fast.
I am trying to join two script
--script 1
select
t.vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+',' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(t.vendor_code) as [No_of_Case]
from
dbo.FTX_FA_CASE t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
t.vendor_code, CLOSED_DATE
and
--script 2
SELECT
(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20)))) + ',')
FROM
efoxsfc.dbo.FTX_FA_Calender
WHERE
1 = 1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
which return data like this:
I want a single script which return this output:
Basically I am trying to get all the data of second table and no_of_Case from 1st table. The month which is not present in 1st script , for that no_of_case value should be "0".
Please advice !!
Try this
select
name,
(select distinct date
from Table_1 t2
where t1.date = t2.date),
count([no of count])
from
Table_1 t1
group by
name, date
I have model Activity, and i am storing timeInterval/NSDate when user does some activity, there could be situation when user will take a break for 15 minutes, and will back. I would like to sum time between activities only if difference is less than 10 minutes between them and measure real time of his work. How can i create NSPredicate to achieve that?
Nailed it for you. What I believe is a good example below.
-- Set Employee ID And Date Required Here
DECLARE #ID INT = 7;
DECLARE #Date SMALLDATETIME = '20150615';
--create our table
DECLARE #TableRows TABLE
(
ID TINYINT,
ActionLog SMALLDATETIME
);
-- Insert some data
INSERT INTO #TableRows
VALUES
(10,'20150615 16:01:00'),
(7,'20150615 16:02:00'),
(7,'20150615 16:04:00'),
(10,'20150615 16:04:00'),
(10,'20150615 16:23:00'),
(10,'20150615 16:25:00'),
(10,'20150615 16:26:00');
-- First CTE for Row Numbers
WITH RowNumCTE
AS
(SELECT
ROW_NUMBER() OVER(ORDER BY ActionLog) AS RowNum
, ActionLog
FROM
#TableRows
WHERE
ID = #ID AND
datediff(day, #Date, ActionLog) = 0
)
-- SUM of all the Minutes
SELECT
SUM(DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog)) as Mins
FROM RowNumCTE t1
LEFT JOIN RowNumCTE t2 ON T1.RowNum = T2.RowNum + 1
WHERE
DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog) < 10
A better, faster example. This uses LEAD window function (Created in SQL 2012).
-- Set Required Date Here
DECLARE #Date SMALLDATETIME = '20150615';
--create our table
DECLARE #TableRows TABLE
(
TableID INT IDENTITY(1,1) PRIMARY KEY,
ID TINYINT,
ActionLog SMALLDATETIME
);
-- Insert some data
INSERT INTO #TableRows
VALUES
(10,'20150615 16:01:00'),
(7,'20150615 16:02:00'),
(7,'20150615 16:04:00'),
(10,'20150615 16:04:00'),
(10,'20150615 16:23:00'),
(10,'20150615 16:25:00'),
(10,'20150615 16:26:00');
-- First CTE for Row Numbers (To force the LEAD first in the QEP)
WITH AllMinsCTE
AS
(SELECT
ID AS EmployeeID,
DATEDIFF(MINUTE, ActionLog, LEAD(ActionLog) OVER(PARTITION BY id ORDER BY id, actionlog)) as Mins
FROM
#TableRows
WHERE
datediff(day, #Date, ActionLog) = 0
)
SELECT
EmployeeID,
SUM(AllMinsCTE.Mins) as Mins FROM AllMinsCTE
WHERE
AllMinsCTE.Mins < 10
Group BY EmployeeID;
(Background: I'm attempting to find the "peak" hour of activity in a series of cameraapis, defined as having the most entries with a start and end date between 1 hour periods (starting with the beginning of the hour) For example, 1:00 to 2:00 may have 8 entries within that timeframe, but 2:00 to 3:00 has 12 entries - so I would want to have it return the 12 entry timeframe.)
I'm having trouble getting associated data from a SELECT query of a group. Here is the code:
def reach_peak_hour_by_date_range(start_date, end_date)
placement_self_device_id = self.device_id
query = <<-SQL
SELECT max(y.num_entries) AS max_entries
FROM
(
SELECT x.starting_hour, count(*) AS num_entries
FROM
(
SELECT date_trunc('hour', visitor_start_time) starting_hour
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) AS x
GROUP BY x.starting_hour
) AS y
SQL
results = Placement.connection.execute(query)
binding.pry
end
Cameraapi have a device_id, visitor_start_time, and visitor_end_time, referenced in the code.
This code successfully returns the max_entries in a 1 hour period, but I can't figure out what to SELECT to get the associated starting_hour to that max_entries. Because it is a group, it requires aggregated functions, which I don't actually need. Any advice?
didnt quite understand the question ... use window functions
select starting_hour , num_entries from (
SELECT starting_hour ,y.num_entries, max(y.num_entries) over() AS max_entries
FROM
(
SELECT x.starting_hour, count(*) AS num_entries
FROM
(
SELECT date_trunc('hour', visitor_start_time) starting_hour
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) AS x
GROUP BY x.starting_hour
) AS y
) as u
where num_entries = max_entries
this query returns all entries associated with peak hour, you can modify it to return only entry count with associated hour selecting hour and count using distinct or grouping
select * from
(
select x.*, max(num_entries) over()as max_num_entries from
(
SELECT Cameraapis.* ,date_trunc('hour', visitor_start_time) as starting_hour, count(*) over( partition by date_trunc('hour', visitor_start_time)) as num_entries
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) as x
) as x where max_num_entries = num_entries