How to clean up SQL expression - informix

The code below compares recv.rcpt_dtim (which is a datetime type) against the current date/time. It calculates an elapsed time resulting in hours and minutes formatted like: "04:22". It took me a while to get it functional, which it is, but it just seems sloppy. Does anyone have any tips to clean it up?
TRIM((((CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL SECOND(9) to
SECOND)/3600)::VARCHAR(12) || ':' || CASE WHEN (MOD(MOD(((CURRENT YEAR TO
MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9) to
MINUTE)::VARCHAR(12)::INT,60),60))<10 THEN "0" ELSE "" END ||
(MOD(MOD(((CURRENT YEAR TO MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9)
to MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12))

Using Informix 12.10.FC12 Developer Edition I can do the following:
CREATE TABLE test_time
(
rcpt_dtim DATETIME YEAR TO SECOND
);
INSERT INTO test_time VALUES ( '2019-05-09 10:01:01' );
INSERT INTO test_time VALUES ( '2019-05-09 10:01:59' );
INSERT INTO test_time VALUES ( '2019-05-09 13:01:00' );
INSERT INTO test_time VALUES ( '2019-05-09 15:01:00' );
INSERT INTO test_time VALUES ( '2019-04-02 22:01:00' );
SELECT
( CURRENT YEAR TO SECOND - rcpt_dtim )::INTERVAL HOUR(9) TO MINUTE AS elapsed
FROM
test_time
;
elapsed
12:47
12:46
9:47
7:47
0:47
888:47

Related

Dynamic SQL Date Header

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

How to use CASE/WHEN in DB2 by using insert in a stored procedure?

I have a stored procedure for DB2, where I want to fill a field named SEASON with W for Winter and S for Summer. The procedure is done, but I can't handle the logic. Can someone show me how this works?
This is for a dimension table in a data warehouse.
INSERT into ABC.TIME_DIMEMSION (
DATE,
SEASON,
QUERTER)
VALUES(
DATE(myDate),
CASE
WHEN MONTH(myDate) = 1 THEN
SET SEASON= 'W';
WHEN MONTH(myDate) = 2 THEN
SET SEASON= 'W';
WHEN MONTH(myDate) = 2 THEN
SET SEASON= 'S';
ELSE
SET SEASON= 'X';
END CASE.
QUARTER(loaddate));
I'm getting an error
Look at the description of the CASE expression which you can use in other statements.
It differs from the Case Statement.
You must use a CASE expression in your case:
INSERT into ABC.TIME_DIMEMSION (
DATE,
SEASON,
QUERTER)
VALUES(
DATE(myDate),
CASE MONTH(myDate)
WHEN 1 THEN 'X'
WHEN 2 THEN 'Y'
ELSE 'Z'
END,
QUARTER(loaddate)
);
-- or
INSERT into ABC.TIME_DIMEMSION (
DATE,
SEASON,
QUERTER)
VALUES(
DATE(current timestamp),
CASE
WHEN MONTH(current timestamp)=1 THEN 'X'
WHEN MONTH(current timestamp)=2 THEN 'Y'
ELSE 'Z'
END,
QUARTER(current timestamp)
);
One way to do it (there are other ways) in a stored procedure:
Note: do not use reserved words for table column-names!
declare v_season varchar(10);
declare v_themonth integer;
set v_themonth = month(somedate);
set v_season = case when v_themonth in (12,1,2) then 'Winter'
when v_themonth in (3,4,5) then 'Spring'
when v_themonth in (6,7,8) then 'Summer'
when v_themonth in (9,10,11) then 'Autumn'
end;
insert into abc.time_dimension( thedate, season)
values ( somedate, v_theseason);

How to sum time between dates if difference is less than 10 minutes

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;

Get corresponding values to a select in a group for PostgreSQL

(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

error line 86 for stored procedure

I am trying to get this stored procedure to work. I have been working for a month straight, was up till 3 last night, and am approaching burnout. I really want to get this to work as we have an ad campaign that we spent hundreds on sending traffic to.
USE [redhotkitties2005db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_rhkprod_lock_items_for_paypal]
#cfuseridid bigint
,#transaction_guid uniqueidentifier = NULL
AS
BEGIN
SET NOCOUNT ON;
declare #tblcartID bigint
,#cfuserid bigint
,#tblproductsid bigint
,#quantity bigint
,#localInventoryID varchar(100)
,#taxologykey bigint
,#name varchar(1000)
,#shortDescription varchar(8000)
,#productDescription varchar(8000)
,#UorLorUL varchar(2)
,#unitPrice money
,#shippingWeight numeric(6, 2)
,#overSize tinyint
,#smallPic1 nvarchar(100)
,#largePic1 nvarchar(100)
,#smallPic2 nvarchar(100)
,#largePic2 nvarchar(100)
,#smallPic3 nvarchar(100)
,#largePic3 nvarchar(100)
SET #transaction_guid = coalesce(#transaction_guid,newid())
declare c1 cursor forward_only for
select rhkProd_tblCart.tablePK AS tblcartID
,rhkProd_tblProducts.productID as tblproductsid
,rhkProd_tblCart.quantity
,rhkProd_tblProducts.localInventoryID
,rhkProd_tblProducts.name
,rhkProd_tblProducts.taxologyKey
,rhkProd_tblProducts.shortDescription
,rhkProd_tblProducts.productDescription
,rhkProd_tblProducts.UorLorUL
,rhkProd_tblProducts.unitPrice
,rhkProd_tblProducts.shippingWeight
,rhkProd_tblProducts.overSize
,rhkProd_tblProducts.smallPic1
,rhkProd_tblProducts.largePic1
,rhkProd_tblProducts.smallPic2
,rhkProd_tblProducts.largePic2
,rhkProd_tblProducts.smallPic3
,rhkProd_tblProducts.largePic3
from rhkProd_tblCart
INNER JOIN rhkProd_tblProducts
on rhkProd_tblCart.tblProductsFK = rhkProd_tblProducts.productID
where rhkProd_tblCart = #cfuserid
open c1
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
begin
while ##fetch_status = 0
insert into rhkprod_tblpaypallock (
,[cfuserid]
,[transaction_guid]
,[timestamp]
,[tblproductsFK]
,[quantity]
,[localInventoryID]
,[name]
,[taxologykey]
,[shortdescription]
,[productdescription]
,[uorlorul]
,[unitprice]
,[shippingweight]
,[oversize]
,[smallpic1]
,[largepic1]
,[smallpic2]
,[largepic2]
,[smallpic3]
,[largepic3]
)
values (
,#cfuserid
,#transaction_guid
,getdate()
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
)
update rhkprod_tblproducts
set quantity = quantity - #quantity
where productid = #tblproductsid
and UorLorUL in ('U','L')
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
close c1
deallocate c1
end
END
Your INSERT statement has a stray comma at the start:
insert into rhkprod_tblpaypallock (
,[cfuserid]
Should be
insert into rhkprod_tblpaypallock (
[cfuserid]
Your VALUES clause also has a stray comma:
values (
,#cfuserid
Should be
values (
#cfuserid

Resources