MDX Query with parameters with multiples values and null value - sql-server

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.

Related

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

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

SQL Server: How to remove a key from a Json object

I have a query like (simplified):
SELECT
JSON_QUERY(r.SerializedData, '$.Values') AS [Values]
FROM
<TABLE> r
WHERE ...
The result is like this:
{ "2019":120, "20191":120, "201902":121, "201903":134, "201904":513 }
How can I remove the entries with a key length less then 6.
Result:
{ "201902":121, "201903":134, "201904":513 }
One possible solution is to parse the JSON and generate it again using string manipulations for keys with desired length:
Table:
CREATE TABLE Data (SerializedData nvarchar(max))
INSERT INTO Data (SerializedData)
VALUES (N'{"Values": { "2019":120, "20191":120, "201902":121, "201903":134, "201904":513 }}')
Statement (for SQL Server 2017+):
UPDATE Data
SET SerializedData = JSON_MODIFY(
SerializedData,
'$.Values',
JSON_QUERY(
(
SELECT CONCAT('{', STRING_AGG(CONCAT('"', [key] ,'":', [value]), ','), '}')
FROM OPENJSON(SerializedData, '$.Values') j
WHERE LEN([key]) >= 6
)
)
)
SELECT JSON_QUERY(d.SerializedData, '$.Values') AS [Values]
FROM Data d
Result:
Values
{"201902":121,"201903":134,"201904":513}
Notes:
It's important to note, that JSON_MODIFY() in lax mode deletes the specified key if the new value is NULL and the path points to a JSON object. But, in this specific case (JSON object with variable key names), I prefer the above solution.

SSRS: Open report with long URL parameters in new window

I have question similar as Open SSRS URL in New Window, but one of my parameters has many values and the URL becomes too long. This parameter always equals such parameter in initial report.
How can I solve it? Can I make post request in "go to url" field or define parameter default value from initial report?
Here is how I reduce the amount of characters passed into my report URL with parameters. Since Microsoft Internet Explorer has a maximum uniform resource locator (URL) length of 2,083 characters you have to get creative.
First, add parameter values for all variables. The other option would be to use a defaults table.
Then union the parameter(s) to the datasets for your other parameters. This way you'll get the all option in your parameter dropdowns.
;WITH
teams_source
AS
(
SELECT tbl.* FROM (VALUES
( 2323304)
, ( 2323305)
, ( 2323306)
, ( 2323307)
, ( 2323308)
, ( 2323309)
, ( 2323310)
, ( 2323311)
, ( 2323312)
, ( 2323313)
, ( 2323314)
, ( 2323315)
, ( 2323316)
) tbl ([Teams])
)
SELECT [Teams], [TeamsFormat] = CAST([Teams] AS VARCHAR) FROM teams_source
UNION
SELECT [Teams] = #all_value_nbr, [TeamsFormat] = #all_value_text
ORDER BY 1
Then in the dataset for your report change the WHERE clause to check for the all variable.
WHERE
1=1
AND (#all_value_nbr IN(#Teams) OR [Teams] IN(#Teams))
When you build the URL with parameters, you can count the number of values.
IIF(Parameters!Teams.Count = Count(Fields!Teams.Value, "TeamsDataset"), "", "#Teams=" + Join(Parameters!Teams.Value, "#Teams="))

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: RANK showing ties, even though data values are different

The original query I had didn't have the [Row Axis] SET which appears below, it worked, but had 'duplicated' ranking values
Someone suggested that I move the row axis, but now instead of 'repeated rank values' I just get #Error showing
What is wrong with my RANK function?
WITH
SET [Row Axis] AS
/*NON EMPTY */
(
Generate
(
[PortfolioBenchmarks]
,TopCount
(
(
[Portfolio].[Portfolio Name].CurrentMember
,[Portfolio Benchmark].[Benchmark Name].CurrentMember
)
*
[Factors]
,10
,Abs([Measures].[FormattedBarraoutput])
)
)
)
SET [Portfolios] AS
{
[Portfolio].[Portfolio Name].&[thingy one]
,[Portfolio].[Portfolio Name].&[thingy two]
,[Portfolio].[Portfolio Name].&[another thingy]
,[Portfolio].[Portfolio Name].&[all these get passed in as params anyhoo]
,[Portfolio].[Portfolio Name].&[one more for luck]
}
SET [PortfolioBenchmarks] AS
{
Filter
(
[Portfolios]
*
[Portfolio Benchmark].[Benchmark Name].Children
,(NOT
IsEmpty([Measures].[Barra Relative Result Percentage]))
)
}
SET [Factors] AS
{
(
[Barra Scenario].[Barra Scenario Name].&[Eff Active Weight (%)]
,[Barra Factor].[Factor Type].&[GICSIndustry]
)
*
[Barra Factor].[Factor Value].Children
}
MEMBER [Measures].[FormattedBarraoutput] AS
IIF
(
IsEmpty([Measures].[Barra Relative Result Percentage])
,NULL
,[Measures].[Barra Relative Result Percentage]
)
MEMBER [Measures].[Ranking] AS
RANK ([Row Axis].CurrentMember,[Portfolios], [Measures].[FormattedBarraoutput])
SELECT
{[Measures].[FormattedBarraoutput],[Measures].[Ranking]} ON COLUMNS
,[Row Axis] ON ROWS
FROM [wobbly_woo]
WHERE
(
[Time].[TimeKey].&[20120131]
);

Resources