How to Pass Data Value to where condition in Snow Flake - snowflake-cloud-data-platform

I have a requirement in which I need pass Current Date value to the where condition of a select statement.
Below is the code:
var step01 = `SELECT CURRENT_DATE::DATE`;
var statement01 = snowflake.createStatement( {sqlText: step01} );
results1 = statement01.execute();
results1.next();
Var1 = results1.getColumnValue(1);
Var2 =`Insert into TableA ( ColA) select ColB from tableB
where cast(LOAD_DTTM as date) >= TO_DATE(''''${Var1}'''')`;
I am getting the following error. Could you please help.
Failed: Code: 100183
State: P0000
Message: Date 'Fri Mar 04 2022 00:00:00 GMT-0800 (Pacific Standard Time)' is not recognized
Stack Trace: undefined
Please advise

Related

SQL issue: Get Previous data based on a action code

I am stuck with this issue.
Please refer to screenshot too for table structure.
SQL ISSUE SCREENSHOT
So we have 2 tables : HISTORY table keeps histiry of payrate, location etc
& POSITION table only gives details of Job action changes datewise.
Desired output we want to only consider Action_code as 'JOB-CHANGE' and get the latest payrate and previous payrate before the action- job change.
--- table1: HISTORY ---
EMPLOYEE
EFFECT_DATE
END_DATE
PAY_RATE
LOCAT_CODE
344
4/1/2021
current - TBD
42.44
ATL
344
3/2/2021
3/31/2021
41.81
ATL
344
3/31/2020
3/1/2021
41.81
DTW
--- table2 ACTION ---
COMPANY
EMPLOYEE
EFFECT_DATE
ACTION_CODE
REASON_01
100
344
3/31/2021
LOA
ST-RTW
100
344
3/2/2021
JOB CHANGE
JC-TRANS(L
100
344
5/31/2020
LOA
ST-COVID90
--- DESIRED OUTPUT --
Employee
Action code
Reason_1
Effective_Date
Previous_Location
Previous_Rate
New_Location
New_Pay_Rate
344
JOB CHANGE
JC-TRANS(L
3/2/2021
DTW
41.81
ATL
42.44
Could you please help me out here. Thanks much :) in advance
You can use OUTER APPLY (SELECT TOP (1) to get the first matching row on or before the date.
Within the APPLY you can use LEAD to access the values on the next row going backwards.
SELECT
a.EMPLOYEE,
[Action code] = h.ACTION_CODE,
a.REASON_01,
Effective_Date = a.EFFECT_DATE,
hPrev.Previous_Location,
hPrev.Previous_Rate,
hNew.New_Location,
hNew.New_Pay_Rate
FROM ACTION a
OUTER APPLY (
SELECT TOP (1)
Previous_Location = h.LOCAT_CODE,
Previous_Rate = h.PAY_RATE
FROM HISTORY h
WHERE h.EFFECT_DATE < a.EFFECT_DATE
AND h.Employee = a.Employee
ORDER BY h.EFFECT_DATE DESC
) hPrev
OUTER APPLY (
SELECT TOP (1)
New_Location = h.LOCAT_CODE,
New_Pay_Rate = h.PAY_RATE,
FROM HISTORY h
WHERE h.EFFECT_DATE > a.EFFECT_DATE
AND h.Employee = a.Employee
ORDER BY h.EFFECT_DATE
) hNew
WHERE a.ACTION_CODE = 'JOB CHANGE';

Converting SQL Server to Snowflake SQL, how do I write the INSERT statement to put data from a query into a temp table?

I am working on converting a SQL Server query to Snowflake SQL. The code creates a dynamic start and end date, creates the temp table, then inserts the data from the query into the temp table.
Here is the query. When I run individual sections separately, I can create the variables and the temp table and the actual query to pull data also works.
However, I have not been able find the correct syntax for the INSERT statement to run correctly. Any help would be appreciated.
SET StartDate = (SELECT DATEADD(month, -24, dim.MONTH_BEGIN_DT)
FROM HI_DB.STG_EPICCLARITY_PHS.DATE_DIMENSION dim
WHERE CAST(GETDATE() AS date) = dim.CALENDAR_DT);
SET EndDate = (SELECT dim2.MONTH_BEGIN_DT
FROM HI_DB.STG_EPICCLARITY_PHS.DATE_DIMENSION dim2
WHERE CAST(GETDATE() AS date) = dim2.CALENDAR_DT);
CREATE TEMPORARY TABLE HI_DB.STG_EPICCLARITY_PHS.A1C_Min_Max
(
PAT_ID VARCHAR(255),
TEST_CNT NUMERIC(18,0),
ORD_ID_MIN NUMERIC(18,0),
ORD_ID_MAX NUMERIC(18,0)
);
INSERT INTO HI_DB.STG_EPICCLARITY_PHS.A1C_Min_Max (PAT_ID, TEST_CNT, ORD_ID_MIN, ORD_ID_MAX)
VALUES
SELECT
oprc.PAT_ID,
COUNT(*) as "TEST_CNT",
MIN(oprc.ORDER_PROC_ID) as "ORD_ID_MIN",
MAX(oprc.ORDER_PROC_ID) as "ORD_ID_MAX"
FROM
HI_DB.STG_EPICCLARITY_PHS.ORDER_PROC oprc
JOIN
HI_DB.STG_EPICCLARITY_PHS.PAT_ENC enc ON oprc.PAT_ENC_CSN_ID = enc.PAT_ENC_CSN_ID
INNER JOIN
HI_DB.STG_EPICCLARITY_PHS.ZC_DISP_ENC_TYPE typ ON enc.ENC_TYPE_C = typ.DISP_ENC_TYPE_C
INNER JOIN
HI_DB.STG_EPICCLARITY_PHS.CLARITY_EAP eap ON oprc.PROC_ID = eap.PROC_ID
INNER JOIN
HI_DB.STG_EPICCLARITY_PHS.ORDER_RESULTS ordres ON oprc.ORDER_PROC_ID = ordres.ORDER_PROC_ID
WHERE
oprc.ORDERING_DATE BETWEEN $StartDate AND $EndDate
AND enc.CONTACT_DATE BETWEEN $StartDate AND $EndDate
AND enc.SERV_AREA_ID = 12288
AND oprc.proc_id IN (12298843, 12299371, 122127749, 10050764, 12018926, 12037733)
AND ordres.COMPONENT_ID = 1202098 -- USE COMPONENT_ID = 1005276 to get ESTIMATED AVERAGE GLUCOSE VALUE
AND LEN(ordres.ORD_VALUE) > 1
GROUP BY
oprc.PAT_ID
SELECT *
FROM HI_DB.STG_EPICCLARITY_PHS.A1C_Min_Max
Try the query without the values keyword.
INSERT INTO A1C_Min_Max (PAT_ID,TEST_CNT,ORD_ID_MIN,ORD_ID_MAX)
SELECT
oprc.PAT_ID,
count(*) "TEST_CNT",
MIN(oprc.ORDER_PROC_ID) "ORD_ID_MIN",
MAX(oprc.ORDER_PROC_ID) "ORD_ID_MAX"
FROM ORDER_PROC oprc
JOIN PAT_ENC enc
ON oprc.PAT_ENC_CSN_ID = enc.PAT_ENC_CSN_ID
INNER JOIN ZC_DISP_ENC_TYPE typ
ON enc.ENC_TYPE_C = typ.DISP_ENC_TYPE_C
INNER JOIN CLARITY_EAP eap
ON oprc.PROC_ID = eap.PROC_ID
INNER JOIN ORDER_RESULTS ordres
ON oprc.ORDER_PROC_ID = ordres.ORDER_PROC_ID
WHERE oprc.ORDERING_DATE BETWEEN $StartDate AND $EndDate
AND enc.CONTACT_DATE BETWEEN $StartDate AND $EndDate
AND enc.SERV_AREA_ID = 12288
AND oprc.proc_id IN (12298843,12299371,122127749,10050764,12018926,12037733)
AND ordres.COMPONENT_ID = 1202098 -- USE COMPONENT_ID = 1005276 to get ESTIMATED AVERAGE GLUCOSE VALUE
AND LEN(ordres.ORD_VALUE) > 1
GROUP BY
oprc.PAT_ID;
Insert
INSERT [ OVERWRITE ] INTO target_table [ ( target_col_name [ , ... ] ) ]
{ { VALUES ( { value | DEFAULT | NULL } [ , ... ] ) [ , ( ... ) ] } | query }
In a VALUES clause, you can specify the following:
value: Inserts the explicitly-specified value.
DEFAULT: Inserts the default value for the corresponding column in the target table.
NULL: Inserts a NULL value.
https://docs.snowflake.com/en/sql-reference/sql/insert.html#required-parameters

SQL: removing a date from from inner SQL statement returns incorrect data

I am trying to figure this one out, but am stuck.
From the below SQL statement, when I run the statement with the commented date, I get the correct result. But when I remove it, the statement returns incorrect data; it omits a few records.
I don't understand why having the date filter and not having it in the statement following the NOT IN produces different results. Also, is there something else I can try other than "not in"?
select
RscMaster_no_in, last_name, first_name, Wstat_Abrv_Ch,
Staffing_Calendar_Date, payhours
from
all_hire
where
Wstat_no_in in (103)
and RscMaster_no_in not in (select t2.RscMaster_no_in
from all_hire h
right join (select h.RscMaster_no_in, last_name, first_name, Staffing_Calendar_Date
from all_hire h
where rscmaster_no_in in (select rscmaster_no_in from ECC_splty)
and Wstat_Abrv_Ch <> ''
and Wstat_no_in = 107) t2 on h.RscMaster_no_in = t2.RscMaster_no_in and h.Staffing_Calendar_Date = t2.Staffing_Calendar_Date
where
h.Wstat_no_in = 103
and h.Staffing_Calendar_Date = '2020-11-01' -- this date is only for testing, and will have to be removed. The SQL statement, however, returns correct data with this filter added.
)
and Staffing_Calendar_Date = '2020-11-01'
From the below SQL statement #1, I get 29 records.
select
RscMaster_no_in, last_name, first_name, Wstat_Abrv_Ch,
Staffing_Calendar_Date, payhours
from
all_hire
where
Wstat_no_in in (103)
and
Staffing_Calendar_Date = '2020-11-01'
From SQL statement #2 below, I get 2 records.
select t2.RscMaster_no_in
from all_hire h
right join (select h.RscMaster_no_in, last_name, first_name,
Staffing_Calendar_Date
from all_hire h
where rscmaster_no_in in (select rscmaster_no_in from ECC_splty)
and Wstat_Abrv_Ch <> ''
and Wstat_no_in = 107) t2 on h.RscMaster_no_in = t2.RscMaster_no_in and
h.Staffing_Calendar_Date = t2.Staffing_Calendar_Date
where
h.Wstat_no_in = 103
and h.Staffing_Calendar_Date = '2020-11-01'
So when I combine these two SQL statements, I get the correct result with the 27 records. It is only when I remove the date from statement #2 that I get the incorrect number of records - 22 records. I checked the records and did not see any issue. I just don't understand why.

How case in SELECT clause can affect the resultset in SQL Server?

I'm facing a strange behavior in SQL Server. I have a query how return 233 rows and it's fine.
The problem is if I add a condition in a CASE, well, she returns 48 rows. How is it possible ? CASE shouldn't change my results : it's a CASE in a SELECT clause and there is no WHERE on it.
See the query below. The part between * ... * is the condition who change the result of the entire query.
SELECT * FROM (
SELECT
CASE
WHEN dq.type_of_cover = 'ndd' AND ah.type_of_cover = 'ndaa' THEN ah.type_of_cover
ELSE dq.type_of_cover
END AS type_of_cover,
CASE
WHEN (dq.type_of_cover = 'CCD' AND dq.result_code = 'CCP') THEN NULL --a.mntgex
WHEN (ah.type_of_cover = 'ndaa' *** AND ah.date = GETDATE() ***) THEN ah.first_amount
ELSE ISNULL(dq.first_amount, 0)
END AS problem,
dq.active
FROM (
SELECT du.coddeb, du.coduti
FROM cacheDebiteurConsolideByUtilisateur AS du
WHERE du.coduti = 4102
) AS debi
INNER JOIN DecisionQueue AS dq ON dq.coddeb = debi.coddeb
OUTER APPLY (
SELECT TOP 1 type_of_cover, MIN(date) AS date, first_amount, coddeb, codadh
FROM AtradiusCLHistory
WHERE codadh = 1003
AND dq.coddeb = coddeb
GROUP BY type_of_cover, first_amount, coddeb, codadh
) AS ah
WHERE dq.codadh = 1003
AND dq.cancelled != 1
) AS test
WHERE type_of_cover = 'ndaa' AND active = 1
So when I got AND ah.date = GETDATE() in the "problem" CASE, I have 48rows, when not, 233.

Get data for each month even if it's null in sql server

In my context, customers are making request and that request are saved in database. For each month, i would like to count the number of requests for each month, so I've tried that :
Select COUNT(EveLngId) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join T_Historique on HisLngEveId = EveLngId, T_Param as TPA
WHERE EveLngDosId = 1062
And EveLngBibId = 268
And HisLngBibId = 267
And ParStrIndex = 'RES'
And TE.EveLngResponsableId = TPA.ParLngId
And EveDatRedaction = EveDatRealisation
And year(EveDatRedaction) = '2013'
group by MONTH(EveDatRedaction)
And I get that result :
So as you see, for that year (2013) I don't have the values for each month, Why ? Because for some of them, the value is 0. There is a way to display the value for each month even if the value is 0 ?
The best solution would be to create a calendar table and JOIN your data. Otherwise, you will need to create a table:
SELECT 1 AS month, 2013 AS year
UNION ALL
SELECT 2, 2013
UNION ALL
SELECT 3, 2013
UNION ALL
SELECT 4, 2013
...
and JOIN it with your query.
Assuming that you have some data for each month (although not matching the where clause), you can use conditional aggregation:
Select sum(case when EveLngDosId = 106 And EveLngBibId = 268 And HisLngBibId = 267
And ParStrIndex = 'RES' And
And EveDatRedaction = EveDatRealisation
then 1 else 0
end) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join
T_Historique
on HisLngEveId = EveLngId join
T_Param as TPA
on TE.EveLngResponsableId = TPA.ParLngId
WHERE year(EveDatRedaction) = '2013'
group by MONTH(EveDatRedaction);
The disadvantage is that this will not use indexes for the where clause.

Resources