AWS Athena Prepare Statements for Arrow Functions- SYNTAX_ERROR: line 1:1: Incorrect number of parameters: expected 1 but found 2 - prepared-statement

I am using AWS Athena,
I have an arrow function(filter) like this.
PREPARE my_select2 FROM
select * from (WITH dataset (json_str) AS (
VALUES (
json '{
"address":{
"streetAddress":"101",
"city":"abc",
"state":"",
"phoneNumbers":[
{
"type":"home",
"number":"11"
},
{
"type":"city",
"number":"4"
}
]
}
}'
)
) -- query
select street_address,
city
from (
select JSON_EXTRACT_SCALAR(json_str, '$.address.streetAddress') as street_address,
JSON_EXTRACT_SCALAR(json_str, '$.address.city') as city,
cast(
JSON_EXTRACT(json_str, '$.address.phoneNumbers') as array(json)
) phones
from dataset
)
where
cardinality(
filter(
phones,
js->json_extract_scalar(js, '$.type') = ? **-- Parameter 1**
and json_extract_scalar(js, '$.number') = '4'
)
) > 0 ) as t where t.city =? **-- Parameter 2**
EXECUTE my_select2 USING 1, 'abc';
When in AWS console, it gives me the error: Please find the screenshot
Error Message: SYNTAX_ERROR: line 1:1: Incorrect number of parameters: expected 1 but found 2

Related

Transpose a array that is in a json file into columns

I have a JSON where in between is an array. I already extracted all the other information in the json but i cant do it with the array in it. IT looks like this in BigQuery and it is a String JSON
{
"description":"Eminem.",
"eDate":{
"_seconds":1673668800,"_nanoseconds":409000000
},
"pId":"test-plan-1",
"Id":"test-p-1",
"startDate":{
"_seconds":1673636400,"_nanoseconds":957000000
},
"Categories":[
{
"description":"Eminem 123.",
"id":"cheap",
"name":"Cheap Ticket", "sEnd":{"_seconds":1767283200,"_nanoseconds":225000000},
"sStart":{"_seconds":1673272800,"_nanoseconds":330000000},
"tRate":0.19,
"uPrice":1.5
}
],
"title":"Apple",
"vId":"test-v-1"
}
The array starts by categories and end by uPrice
Im expecting that all keys with their values have their own column . The data from JSON and from the array
One possible way would be using JSON_QUERY_ARRAY with ARRAY_TO_STRING. JSON_QUERY_ARRAY returns ARRAY<STRING> which cannot be directly parsed again.
Below is the result of the following query.
WITH
json_dataset AS (
SELECT '{"description":"Eminem.","eDate":{"_seconds":1673668800,"_nanoseconds":409000000},"pId":"test-plan-1","Id":"test-p-1","startDate":{"_seconds":1673636400,"_nanoseconds":957000000},"Categories":[{"description":"Eminem 123.","id":"cheap","name":"Cheap Ticket", "sEnd":{"_seconds":1767283200,"_nanoseconds":225000000},"sStart":{"_seconds":1673272800,"_nanoseconds":330000000},"tRate":0.19,"uPrice":1.5}],"title":"Apple","vId":"test-v-1"}' as json_string
)
SELECT
json_string,
JSON_VALUE(
json_string,'$.description'
) AS json_value_col,
JSON_QUERY_ARRAY(
json_string,'$.Categories'
) AS json_query_array_col,
ARRAY_TO_STRING(
JSON_QUERY_ARRAY(
json_string,'$.Categories'
),
""
) AS json_array_string,
JSON_VALUE(
ARRAY_TO_STRING(JSON_QUERY_ARRAY(json_string,'$.Categories'),""),'$.description'
) AS target_example,
FROM json_dataset
;

Postgresql how to select a value from multiple jsons inside a array on a jsonB column

I have this table
create table <table_name>(attr jsonb)
And this is the data inside
{
"rules": [
{
"id": "foo",
"name": "test_01",
...
},
{
"id": "bar",
"name": "test_02",
...
}
]
}
What I want is to select both names, what I have accomplished so far is this
select attr -> 'rules' -> 0 -> 'name' from <table_name>;
which returns test_01
select attr -> 'rules' -> 1 -> 'name' from <table_name>;
which returns test_02
I want to return something like this:
test_01,test_02
or if it's possible to return them in multiple lines, that would be even better
This is a sample data to show my problem, for reasons beyond my control, it's not possible to store each rule on a distinct line
You can use jsonb_array_length together with generate_series to get each name. Then use string_agg to aggregate list of names. Without plpgsql and with a single statement. (see demo)
with jl(counter) as ( select jsonb_array_length(attr->'rules') from table_name )
select string_agg(name,' ') "Rule Names"
from (select attr->'rules'-> n ->> 'name' name
from table_name
cross join ( select generate_series(0,counter-1) from jl ) gs(n)
) rn;
if anyone else get stuck on a situation like this, this is the solution the I found
create or replace function func_get_name() RETURNS text
language 'plpgsql'
AS $$
declare
len character varying(255);
names character varying(255);
res character varying(255);
begin
select jsonb_array_length(attr->'rules') into len from <table_name>;
res := '';
for counter in 0..len loop
select attr->'rules'-> counter ->> 'name'
into names
from <table_name>;
if names is not null then
res := res || ' ' || names;
end if;
end loop;
return res;
end;
$$
select func_get_name();
it's a solution: yes, it's a good solution: I have no ideia

Postgresql: Custom Type + Arrays combination

I'm unable to find where the issue is for the below program. the values of the custom type are displaying without any errors when I use RAISE NOTICE statements at the end. When I run the final select statement, the error is Array value must start with "{" or dimension information. Please help me with the select statement on how to call the package/function.
create
or
replace TYPE t_col_foo as object
(
ID NUMBER
, CLUSTERNAME VARCHAR2(300)
, "1200AM" varchar2(10));
create
or
replace TYPE T_COL_R AS TABLE OF t_col_foo;
CREATE OR REPLACE PACKAGE foo_avail_pkg
IS
FUNCTION foo_slots
(
p_ref_data anyarray
)
RETURN t_col_r[];
END foo_avail_pkg;
CREATE OR REPLACE PACKAGE BODY foo_avail_pkg
IS
FUNCTION foo_slots
(
p_ref_data anyarray
)
RETURN t_col_r[]
IS
-- declare
r_target_data t_col_foo:=t_col_foo(null,null,null);
r_target_data_1 t_col_foo;
r_source_data text[];
t_return t_col_tab1;
BEGIN
t_return:=t_col_tab1();
select
array
(
select
unnest( p_ref_data )
)
into r_source_data
;
-- r_target_data = '{}';
for i in coalesce(array_lower(r_source_data,1),0) .. coalesce(array_upper(r_source_data,1),0)
LOOP
r_target_data.ID := substr(r_source_data[i],1,instr(r_source_data[i],',',1,1)-1);
r_target_data.CLUSTERNAME := substr(r_source_data[i],length(r_target_data.ID)+2,(instr(r_source_data[i],',',length(r_target_data.ID)+1,2) - instr(r_source_data[i],',',1,1))-1);
r_target_data."1200AM" := 3;
r_target_data_1 :=row(r_target_data.ID ,r_target_data.CLUSTERNAME,r_target_data."1200AM") :: t_col_foo;
END LOOP;
-- dbms_output.put_line(r_target_data_1);
RETURN r_target_data_1;
end;
END foo_avail_pkg;
This is how I have to call
select * from foo_avail_pkg.foo_SLOTS(array
(
select
ID
||','
||CLUSTER_NAME
||','
||LOB
from
y limit 1
));
And the error is
ERROR: malformed array literal: "(1398,Sanity20feb,3)"
DETAIL: Array value must start with "{" or dimension information.

The STRTOSET function expects a tuple set expression for the 1 argument. A string or numeric expression was used

I'm using reporting services, using parameters, so I have query like this:
SELECT
NON EMPTY { [Measures].[ReclamosBSC_Reclamos] } ON COLUMNS,
NON EMPTY { ([Dim_Tiempo_].[Anio].[Anio].ALLMEMBERS
* [Dim_Tiempo_].[Mes].[Mes].ALLMEMBERS
* [Dim_Tiempo_].[NombreMesAbreviado].[NombreMesAbreviado].ALLMEMBERS
* [Dim_PlantaCentro_].[IdGrupo].[IdGrupo].ALLMEMBERS
* [Dim_PlantaCentro_].[NombreGrupo].[NombreGrupo].ALLMEMBERS
* [Dim_PlantaCentro_].[IdDivision].[IdDivision].ALLMEMBERS
* [Dim_PlantaCentro_].[NombreDivision].[NombreDivision].ALLMEMBERS
* [Dim_PlantaCentro_].[IdPlanta].[IdPlanta].ALLMEMBERS
* [Dim_PlantaCentro_].[Planta].[Planta].ALLMEMBERS
* [Dim_ClientePadre_].[Dim_ClientePadre_].[Dim_ClientePadre_].ALLMEMBERS ) }
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_VALUE, MEMBER_UNIQUE_NAME ON ROWS
FROM
(
SELECT
( STRTOSET(#DimTiempoMes) ) ON COLUMNS
FROM
(
SELECT
( STRTOSET(#DimTiempoAnio) ) ON COLUMNS
FROM
[BSC]
)
)
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS
It runs correctly when I use query designer, but when I try to see Preview of my report it returns:
The STRTOSET function expects a tuple set expression for the 1
argument. A string or numeric expression was used.
Can someone explain me what is wrong with my query?
Assuming that the Preview functionality is setting your year and month parameter values to "2017" and "9", respectively, you can rewrite your query as follows:
SELECT
NON EMPTY { [Measures].[ReclamosBSC_Reclamos] } ON COLUMNS,
NON EMPTY { ([Dim_Tiempo_].[Anio].[Anio].ALLMEMBERS
* [Dim_Tiempo_].[Mes].[Mes].ALLMEMBERS
* [Dim_Tiempo_].[NombreMesAbreviado].[NombreMesAbreviado].ALLMEMBERS
* [Dim_PlantaCentro_].[IdGrupo].[IdGrupo].ALLMEMBERS
* [Dim_PlantaCentro_].[NombreGrupo].[NombreGrupo].ALLMEMBERS
* [Dim_PlantaCentro_].[IdDivision].[IdDivision].ALLMEMBERS
* [Dim_PlantaCentro_].[NombreDivision].[NombreDivision].ALLMEMBERS
* [Dim_PlantaCentro_].[IdPlanta].[IdPlanta].ALLMEMBERS
* [Dim_PlantaCentro_].[Planta].[Planta].ALLMEMBERS
* [Dim_ClientePadre_].[Dim_ClientePadre_].[Dim_ClientePadre_].ALLMEMBERS ) }
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_VALUE, MEMBER_UNIQUE_NAME ON ROWS
FROM
(
SELECT
{ ( STRTOMEMBER('[Dim_Tiempo_].[Mes].[Mes].[' + #DimTiempoMes + ']') ) } ON COLUMNS
FROM
(
SELECT
{ ( STRTOMEMBER('[Dim_Tiempo_].[Anio].[Anio].[' + #DimTiempoAnio + ']') ) } ON COLUMNS
FROM
[BSC]
)
)
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS
Using nested subqueries will allow you to include the year and month on your ROWS axis in the SELECT clause. If you used a WHERE clause, you would get an error when including the year and month in the SELECT clause.

MDX Query with parameters with multiples values and null value

I work with a SSAS Cube and Datazen (dashboard creator). I've a data view (for the valueCode 'AZE') with 3 parameters:
AgeClassCode: 'AGE01', 'AGE02', 'AGE03', ...
StatutCode: 'A', 'B', 'C', 'D', ...
NiveauCode: 'X', 'Y', 'W', ...
With this query, when I use multiple values or just one value for each, it works.
But I would like that the query returns all values for a parameter when the parameter's value is null. I've tested ISEMPTY(#param), ISEMPTY(STRTOSET(#param)), ... but that returns this error:
An mdx expression was expected. An empty expression was specified.
This query works for one or more values:
SELECT
NON EMPTY
{
[Measures].[Value], [Measures].[PreviousValueYear], [Measures].[PreviousValueReportMonth]
} ON COLUMNS,
NON EMPTY
{
NONEMPTY
(
[EntiteFederal].[ServiceCode].[ServiceCode].ALLMEMBERS *
[EntiteFederal].[EntiteCode].[EntiteCode].ALLMEMBERS *
[ReportMonth].[ReportMonth].[ReportMonth].ALLMEMBERS *
[T].[Year].[Year].ALLMEMBERS
)
} DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
FROM
(
SELECT ( { [ValueType].[ValueCode].&[AZE] } ) ON COLUMNS
FROM (
SELECT ( STRTOSET('{{ #AgeClassCode }}') ) ON COLUMNS
FROM (
SELECT ( STRTOSET('{{ #NiveauCode }}') ) ON COLUMNS
FROM
(
SELECT ( (STRTOSET('{{ #StatutCode }}') ) ON COLUMNS
FROM [MyCube]
)
)
)
)
WHERE
(
IIF( STRTOSET('{{ #StatutCode }}').Count = 1, STRTOSET('{{ #StatutCode }}'), [Statut].[StatutCode].currentmember ),
IIF( STRTOSET('{{ #NiveauCode }}').Count = 1, STRTOSET('{{ #NiveauCode }}'), [Niveau].[NiveauCode].currentmember ),
IIF( STRTOSET('{{ #AgeClassCode }}').Count = 1, STRTOSET('{{ #AgeClassCode }}'), [AgeClass].[AgeClassCode].currentmember ),
[ValueType].[ValueCode].&[AZE]
)
What do I have to change?
EDIT:
To test the strtoset()
, the good solution is the
isError()
When using strToSet or strToMember you need to supply a string that represents valid mdx so for example these are ok:
strToSet("[AgeClassCode].[AgeClassCode].members")
strToMember("[AgeClassCode].[AgeClassCode].[AGE01]")
This isn't valid as NULL isn't a string, or something that represents mdx:
strToSet(NULL)
So if in your client you'd like NULL to represent all members then somehow you need to transform the NULL to a string "[AgeClassCode].[AgeClassCode].members" before it hits strToSet.

Resources