how to add date in Teradata? - date

Hi i want to add 01/01/1970 to a column ,datatype of last_hit_time_gmt is bigint ,when i run the below query i am getting data type
last_hit_gmmt
does not match a defined datatype name.
select
distinct STG.OMN_APND_KEY,
STG.last_hit_time_gmt,
IIF(STG.last_hit_time_gmt <>0,ADD_TO_DATE(TO_DATE('01/01/1970', 'DD/MM/YYYY'),'SS',cast(STG.last_hit_time_gmt as DATE ),NULL)
from EDW_STAGE_CDM_SRC.STG_OMNITUREDATA STG
WHERE
UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE') and
STG.OMN_APND_KEY='61855975'
please help me..

The query and data type is incompatible with Teradata.
As stated in the comments you may want to use "CASE" instead of "IFF". The general format is
CASE WHEN *condition* THEN *result_if_true*
ELSE *result_if_false*
END as *ColumnName*
editing based on comment response
So in your query example the case statement can be used like...
select distinct STG.OMN_APND_KEY
,STG.last_hit_time_gmt
,CASE WHEN STG.last_hit_time_gmt = 0 THEN NULL
ELSE DATE '1970-01-01'
END AS YourColName
FROM EDW_STAGE_CDM_SRC.STG_OMNITUREDATA STG
WHERE UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE') and
STG.OMN_APND_KEY='61855975'
Also, if you are merely just trying to update the field STG.last_hit_time_gmt, why not just use two simple UPDATE statements?
UPDATE EDW_STAGE_CDM_SRC.STG_OMNITUREDATA
SET STG.last_hit_time_gmt = DATE '1970-01-01'
WHERE STG.last_hit_time_gmt <> 0
AND UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE')
AND STG.OMN_APND_KEY='61855975';
UPDATE EDW_STAGE_CDM_SRC.STG_OMNITUREDATA
SET STG.last_hit_time_gmt = NULL
WHERE STG.last_hit_time_gmt = 0
AND UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE')
AND STG.OMN_APND_KEY='61855975';

Related

case when in where clause postresql

select service_code,service_cat_code,mobile_no,upper(applicant_name_eng) as name,to_char(license_date,'dd/mm/yyyy')as license_from,to_char(license_valid_upto,'dd/mm/yyyy')as license_to,Upper(license_no),district_code,taluk_code,CONCAT(address_building,', ', address_cityvillage,', ',address_locality,', ',address_landmark,', ',address_street) as address
from mst_license
WHERE cast(license_valid_upto as date) = case
WHEN license_valid_upto < now()
THEN
case
when license_valid_upto = '2021-06-30'
then 1 else 0
END
ELSE
case when license_valid_upto > now()
then 1 else 0
End
END
and Upper(license_no)='1SP146924BJP'
I want license valid should be either greater than now or if license valid less than now it must be with the date ''30/06/2021' but when i use above query i get error
ERROR: operator does not exist: date = integer
LINE 3: WHERE cast(license_valid_upto as date) = case
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 418
Help me out guys
The main issue you have is that your case statement returns an integer (1 or 0) but you are trying to compare that to a date, which you cannot do as Postgres is a strict data typing. Even if it did work it would always be false (well except for 1969-12-31/1970-01-01). Moreover the case structure is not needed. The best/correct to compare dates is just use date values. Since you did not indicate the data type for column license_valid_upto so based on how it is used I'll assume it is timestamp with timezone as that is what NOW() returns. Your query becomes:
select service_code
, service_cat_code
, mobile_no
, upper(applicant_name_eng) as name
, to_char(license_date,'dd/mm/yyyy')as license_from
, to_char(license_valid_upto,'dd/mm/yyyy')as license_to
, upper(license_no) as license_no
, district_code
, taluk_code
, concat(address_building,', '
,address_cityvillage,', '
,address_locality,', '
,address_landmark,', '
,address_street) as address
from mst_license
where and upper(license_no)='1SP146924BJP'
and ( cast(license_valid_upto as date) > cast( now() as date)
or (cast (icense_valid_upto as date) < cast( now() as date)
and cast (icense_valid_upto as date) = date '2021-06-30'
)
);
Also, learn for format your queries for readability and so you do not need to scroll right. You, and others looking at your queries later will appreciate it later.

Exclude where clause based on function specification

I developed the following function:
create function kv_fn_ValuationPerItem_AW (#dDate date, #active bit)
returns table
as
return
(
select
Code ItemCode
, Description_1 ItemDescription
, ItemGroup
, Qty_On_Hand CurrentQtyOnHand
, AveUCst CurrentAvgCost
, Qty_On_Hand*AveUCst CurrentValue
from _bvSTTransactionsFull t
inner join StkItem s on t.AccountLink = s.StockLink
where ServiceItem = 0
and ItemActive = #active
and TxDate <= #dDate
group by Code, Description_1, ItemGroup, Qty_On_Hand, AveUCst
)
The function requires two parameters:
Date
Is the item Active - 1 = Active & 0 = Inactive
If I use the function as stipulated above, by specifying 1 for the Active Parameter, then the results will only be for Active Items.
If I specify 0, then it'll return all inactive Items.
How do I alter this function to cater for Active Items or both Active & Inactive?
i.e. if the parameter is 1, the where clause should read as ItemActive = #active, but when it's 0, the where clause should read as ItemActive in (1,0), How do I change the function to work like this?
I tried a case, but my syntax is not correct...
It's as simple as adding an or to your where cluase:
...
and (ItemActive = 1 OR #active = 0)
...
BTW, you might want to do it like this instead:
and (ItemActive = #active OR #active IS NULL)
which means that when you pass in 1 as #active you'll get only the active items, when you pass in 0 you'll get only the inactive members, but when you pass in null you'll get all records, regardless of the value in the ItemActive column.
Thanks Shnugo & Zohar for your answers,
Please amend your answers, then I'll mark yours as the answer.
The solution to my problem was to alter the Function as following:
create function kv_fn_ValuationPerItem_AW (#dDate date, #active bit)
returns table
as
return
(
select
Code ItemCode
, Description_1 ItemDescription
, ItemGroup
, Qty_On_Hand CurrentQtyOnHand
, AveUCst CurrentAvgCost
, Qty_On_Hand*AveUCst CurrentValue
from _bvSTTransactionsFull t
inner join StkItem s on t.AccountLink = s.StockLink
where ServiceItem = 0
and ItemActive in (1,#active)
and TxDate <= #dDate
group by Code, Description_1, ItemGroup, Qty_On_Hand, AveUCst
)
I think you are looking for this:
DECLARE #mockup TABLE(ID INT IDENTITY,SomeValue VARCHAR(100),Active BIT);
INSERT INTO #mockup VALUES('Row 1 is active',1)
,('Row 2 is active',1)
,('Row 3 is inactive',0)
,('Row 4 is inactive',0);
DECLARE #OnlyActive BIT=0; --set this to 1 to see active rows only
SELECT *
FROM #mockup m
WHERE (#OnlyActive=0 OR m.Active=1);
The idea is: If the parameter is set to 0 this expression is always true, if not, the column Active must be set to 1.
Hint: I used paranthesis, which was not needed in this simple case. But in your more complex WHERE clause they will be needed...
Hint2: I named the parameter OnlyActive, which expresses a bit better what you are looking for. You might turn the parameter to ShowAll with an invers logic too...

Having a crystal report parameter as a declared SQL Value

I'm assuming this is a simple question, but I don't know Crystal Reports very well. I made a SQL Query which uses the declared dates fields of #beginning_date and #ending_date and I want Crystal to prompt for those fields when run. I added the paramter field in crystal and named it the same thing, but I'm unsure how to get them to sync up. My code is below. Thank you in advance.
--/*
DECLARE #beginning_date char(20)
DECLARE #ending_date char(20)
--SELECT #ending_date = '07/31/2016' --23:59:59'
--SELECT #beginning_date = '07/01/2016' --00:00:01'
--*/
SELECT --Sum(CASE when Billing_Ledger.subtype in ('BI','ND') then
--Billing_Ledger.amount ELSE 0 END) as 'Charges'
Patient_Clin_Tran.Clinic_id, Patient_Clin_Tran.service_id, Patient_Clin_Tran.program_id, Patient_Clin_Tran.protocol_id, billing_ledger.amount
FROM Billing_Ledger
JOIN Patient_Clin_Tran ON
Billing_Ledger.clinical_transaction_no = Patient_Clin_Tran.clinical_transaction_no
JOIN Coverage_Plan ON
Billing_Ledger.coverage_plan_id = Coverage_Plan.coverage_plan_id
and Billing_Ledger.hosp_status_code = Coverage_Plan.hosp_status_code
JOIN Payor ON
Coverage_Plan.payor_id = Payor.payor_id
WHERE ( Coverage_Plan.billing_type <> 'CAP' or Coverage_Plan.billing_type is null )
and Billing_Ledger.accounting_date >= #beginning_date
and Billing_Ledger.accounting_date < dateadd(day, 1, #ending_date)
and Patient_Clin_Tran.Clinic_id = 'NP' and payor.name = 'Mainecare' and (Billing_Ledger.subtype in ('BI','ND'))
--GROUP BY Patient_Clin_Tran.Clinic_id, Patient_Clin_Tran.service_id, Patient_Clin_Tran.program_id, Patient_Clin_Tran.protocol_id --, Payor.Name, billing_ledger.amount, payor.type
ORDER BY Patient_Clin_Tran.Clinic_id, Patient_Clin_Tran.service_id, Patient_Clin_Tran.program_id, Patient_Clin_Tran.protocol_id
Firstly you should turn your query into a stored procedure thus:
CREATE PROCEDURE [dbo].[mySPName]
#beginning_date date,
#ending_date date
AS
SELECT Patient_Clin_Tran.Clinic_id, Patient_Clin_Tran.service_id, Patient_Clin_Tran.program_id, Patient_Clin_Tran.protocol_id, billing_ledger.amount
etc.
Now when adding the database connection to your CR report file, after selecting your server and database you will see three options tables, views and stored procedures. Simply select the new procedure from the list. CR will now automtically add the parameters, and will prompt you for values. If you leave the values blank, then at runtime CR will automatically prompt the user for these values.
You will also note that I changed the type of the parameters to date; this is necessary so that CR knows to include a calendar selector in the parameter prompt.

Column is of type timestamp without time zone but expression is of type character

I'm trying to insert records on my trying to implement an SCD2 on Redshift
but get an error.
The target table's DDL is
CREATE TABLE ditemp.ts_scd2_test (
id INT
,md5 CHAR(32)
,record_id BIGINT IDENTITY
,from_timestamp TIMESTAMP
,to_timestamp TIMESTAMP
,file_id BIGINT
,party_id BIGINT
)
This is the insert statement:
INSERT
INTO ditemp.TS_SCD2_TEST(id, md5, from_timestamp, to_timestamp)
SELECT TS_SCD2_TEST_STAGING.id
,TS_SCD2_TEST_STAGING.md5
,from_timestamp
,to_timestamp
FROM (
SELECT '20150901 16:34:02' AS from_timestamp
,CASE
WHEN last_record IS NULL
THEN '20150901 16:34:02'
ELSE '39991231 11:11:11.000'
END AS to_timestamp
,CASE
WHEN rownum != 1
AND atom.id IS NOT NULL
THEN 1
WHEN atom.id IS NULL
THEN 1
ELSE 0
END AS transfer
,stage.*
FROM (
SELECT id
FROM ditemp.TS_SCD2_TEST_STAGING
WHERE file_id = 2
GROUP BY id
HAVING count(*) > 1
) AS scd2_count_ge_1
INNER JOIN (
SELECT row_number() OVER (
PARTITION BY id ORDER BY record_id
) AS rownum
,stage.*
FROM ditemp.TS_SCD2_TEST_STAGING AS stage
WHERE file_id IN (2)
) AS stage
ON (scd2_count_ge_1.id = stage.id)
LEFT JOIN (
SELECT max(rownum) AS last_record
,id
FROM (
SELECT row_number() OVER (
PARTITION BY id ORDER BY record_id
) AS rownum
,stage.*
FROM ditemp.TS_SCD2_TEST_STAGING AS stage
)
GROUP BY id
) AS last_record
ON (
stage.id = last_record.id
AND stage.rownum = last_record.last_record
)
LEFT JOIN ditemp.TS_SCD2_TEST AS atom
ON (
stage.id = atom.id
AND stage.md5 = atom.md5
AND atom.to_timestamp > '20150901 16:34:02'
)
) AS TS_SCD2_TEST_STAGING
WHERE transfer = 1
and to short things up, I am trying to insert 20150901 16:34:02 to from_timestamp and 39991231 11:11:11.000 to to_timestamp.
and get
ERROR: 42804: column "from_timestamp" is of type timestamp without time zone but expression is of type character varying
Can anyone please suggest how to solve this issue?
Postgres isn't recognizing 20150901 16:34:02 (your input) as a valid time/date format, so it assumes it's a string.
Use a standard date format instead, preferably ISO-8601. 2015-09-01T16:34:02
SQLFiddle example
Just in case someone ends up here trying to insert into a postgresql a timestamp or a timestampz from a variable in groovy or Java from a prepared statement and getting the same error (as I did), I managed to do it by setting the property stringtype to "unspecified". According to the documentation:
Specify the type to use when binding PreparedStatement parameters set
via setString(). If stringtype is set to VARCHAR (the default), such
parameters will be sent to the server as varchar parameters. If
stringtype is set to unspecified, parameters will be sent to the
server as untyped values, and the server will attempt to infer an
appropriate type. This is useful if you have an existing application
that uses setString() to set parameters that are actually some other
type, such as integers, and you are unable to change the application
to use an appropriate method such as setInt().
Properties props = [user : "user", password: "password",
driver:"org.postgresql.Driver", stringtype:"unspecified"]
def sql = Sql.newInstance("url", props)
With this property set, you can insert a timestamp as a string variable without the error raised in the question title. For instance:
String myTimestamp= Instant.now().toString()
sql.execute("""INSERT INTO MyTable (MyTimestamp) VALUES (?)""",
[myTimestamp.toString()]
This way, the type of the timestamp (from a String) is inferred correctly by postgresql. I hope this helps.
Inside apache-tomcat-9.0.7/conf/server.xml
Add "?stringtype=unspecified" to the end of url address.
For example:
<GlobalNamingResources>
<Resource name="jdbc/??" auth="Container" type="javax.sql.DataSource"
...
url="jdbc:postgresql://127.0.0.1:5432/Local_DB?stringtype=unspecified"/>
</GlobalNamingResources>

need to translate specific t-sql case in pl/sql

Can anyone tell me how to translate the following T-SQL statement:
SELECT fileld1 = CASE
WHEN T.option1 THEN -1
ELSE
CASE WHEN T.option2 THEN 0
ELSE 1
END
END
FROM Table1 AS T
The point is I need to validate two different options from the table for a single field in the select statement..
I have tried to do somthing with an IF statement in pl/sql, but it just doesnt work for me:
SELECT IF T.option1 THEN -1
ELSE IF T.option2 THEN 0
ELSE 1
END
FROM Table1 AS T
I am not actually sure how to write IF statement inside the SELECT statement..
And also, I need to do it INSIDE the select statement because I am constructing a view.
Use:
SELECT CASE
WHEN T.option1 = ? THEN -1
WHEN T.option2 = ? THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
I can't get your original TSQL to work - I get:
Msg 4145, Level 15, State 1, Line 4
An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
...because there's no value evaluation. If you're checking if the columns are null, you'll need to use:
SELECT CASE
WHEN T.option1 IS NULL THEN -1
WHEN T.option2 IS NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
...or if you need when they are not null:
SELECT CASE
WHEN T.option1 IS NOT NULL THEN -1
WHEN T.option2 IS NOT NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
CASE expressions shortcircuit - if the first WHEN matches, it returns the value & exits handling for that row - so the options afterwards aren't considered.
If I remember correctly, PL/SQL also supports the case. You just would have to move the column alias from "field1=" before the expression to "AS filed1" after the expression.