Tableau add filter inside calculated field - data-visualization

In Tableau i have a calculated field like this below:
COUNTD(
IF(
MONTH([Dataevent]) == 4
) THEN [Id] end)
/
COUNTD(
IF(
YEAR([Dataevento]) == 2018
) THEN [Id] end)
i would like to add a filter to automatically select from the sheet the month and the year without hardcoding them, like this:
COUNTD(
IF(
MONTH([Dataevent]) == filter
) THEN [Id] end)
/
COUNTD(
IF(
YEAR([Dataevento]) == filter
) THEN [Id] end)
how should i do?

You can do it with parameters.
You have to
create a parameter
use it inside your calculated field
Add a filter control to the parameter
You can find a good tutorial following this link.

Related

is it possible to store a table into a DAX variable conditionally

I'd like to store a table in a variable, but based on conditions of the visual.
e.g.
VAR ColumnValues = values( SpecificTable[SpecificColumn] )
works fine, but what I'd like to do is:
VAR ColumnValues = if([some condition T/F], values( SpecificTable1[SpecificColumn1] ) , SpecificTable2[SpecificColumn2] )
For reference, this question is in exploration of workarounds to solve question: Dynamic measure that responds to dynamic dimension which I marked as answered prematurely. I still do not have a solution to dynamically work with column values in DAX.
I've not been able to work out a syntax that allows this. Switch only returns scalar strings, and IF seems to only allow for a scalar result, not a table. Any other options I'm not thinking of?
Was not explicitly using any condition, but the condition that I was checking for, that I was able to get the desired result with the following:
Create Field Parameter (name it "_Dimension"), selecting the columns that need to be in play in the DAX
DAX looks like this:
VAR SelectedDim = SELECTEDVALUE( _Dimension[_Dimension Fields] ) //fully qualified - created by field parameter
//stage the values in each of the columns available
VAR Dim1Values = ADDCOLUMNS( VALUES( Dim1[Column1] ) , "RowValue" , Dim1[Column1] , "ColumnName" , "'Dim1'[Column1]" )
VAR Dim2Values = ADDCOLUMNS( VALUES( Dim1[Column2] ) , "RowValue" , Dim1[Column2] , "ColumnName" , "'Dim1'[Column2]" )
//... same pattern, as many column as needed
VAR SelectedDimValues = FILTER( UNION( Dim1Values, Dim2Values ) , [RowValue] = SelectedDim ) //return the values just for the selected column
SelectedDimValues is a Variable that contains a table with the rows from my selected dimension.

How to add conditional statement inside SQL query?

Hi I am working on one SQL query. Below is my method name which executes query.
private string GetAggregatedOptionParametersByStyleIdCommand(string styleId, bool currentStore)
{
SELECT
opts.style, opts.option::text as {OptionKey}, opts.primary_colour, opts.secondary_colour, opts.brand_description, opts.description, params.*,
CASE WHEN {currentStore} == true THEN
FROM
rex.options opts
JOIN
rex.product_atoms atoms ON atoms.option_id = opts.option
JOIN
rex.parameters params ON atoms.id = params.product_atom_id
JOIN
rex.stores stores ON params.store = stores.id
WHERE
opts.style = '{styleId}'
}
Below is the structure of stores table.
CREATE TABLE rex.stores (
id serial NOT NULL,
close_date timestamp NOT NULL,
country text NULL,
distribution_centre text NULL,
"name" text NULL,
open_date timestamp NOT NULL,
CONSTRAINT "PK_stores" PRIMARY KEY (id)
);
So what I am trying to make is, Whenever the currentStore is true then I want to return the current store. Condition to check currentStore is
store.OpenDate <= currentDate &&
store.CloseDate >= currentDate
Whenever the currentStore is false I want to return all store. To check all store condition is
store.CloseDate >= currentDate
I am trying to add these conditions inside SQL query. I have added CASE WHEN {currentStore} == true THEN I am not sure how to add my closed store condition. Can anyone help me to complete this query? Any help would be appreciated. Thank you.
If you want to check for another possibility you can either add another WHEN or ELSE condition to your CASE statement. These need to come before the END.
For example:
CASE
WHEN x < 0 THEN 'negative'
WHEN x > 0 THEN 'positive'
ELSE 'zero'
END
I am not familiar with postgres, you may not need an END, and you may also be able to say CASE x WHEN > 0 THEN... WHEN < 0 ... meaning you only need to mention x once after CASE; again, this may not be a thing in postgres.

Is there a way to return the currently logged on ID from Netezza in a view's SQL, current_sid

I have a SQL statement on Netezza that uses the following SQL to acquire the currently logged on user ID:
SELECT SESSION_USERNAME FROM _V_SESSION_DETAIL WHERE SESSION_ID=current_sid
This works great when I'm executing the SQL in a database client. However, when I implement the above SQL in a view (along with other SQL) the current_sid is replaced with the session ID I happened to have when I created the view. That SQL will then look something like:
SELECT DEFINITION_SCHEMA."_V_SESSION_DETAIL".SESSION_USERNAME FROM DEFINITION_SCHEMA."_V_SESSION_DETAIL" WHERE (DEFINITION_SCHEMA."_V_SESSION_DETAIL".SESSION_ID = 2434740
Is there a way to define a view that will get the currently logged on user's ID, not the ID that was assigned when the view was created?
Seems like Netezza Metadata functions(ex. current_sid) are not supported in with clause and would advice to remove them from with and to include them in the base query .
CREATE
OR REPLACE VIEW ADMIN.VW_PI_HRCHY_EPH AS
WITH CHAR_MASK(CHAR_MASK_CHAR) AS (
SELECT 'xxx'
FROM _V_SESSION_DETAIL LIMIT 1
)
,NUM_MASK(NUM_MASK_NUM) AS (
SELECT - 1
FROM _V_SESSION_DETAIL LIMIT 1
)
,TS_MASK(TS_MASK_TS) AS (
SELECT '1000-01-01 00:00:00'
FROM _V_SESSION_DETAIL LIMIT 1
)
SELECT CASE
WHEN SECURITY_GRP_CNT.COUNT > 0
THEN PI_HRCHY.HRCHY_LINE_ID
ELSE NUM_MASK.NUM_MASK_NUM
END AS HRCHY_LINE_ID
,CASE
WHEN SECURITY_GRP_CNT.COUNT > 0
THEN PI_HRCHY.LOCALE_CD
ELSE CHAR_MASK.CHAR_MASK_CHAR
END AS LOCALE_CD
,CASE
WHEN SECURITY_GRP_CNT.COUNT > 0
THEN PI_HRCHY.MODIFY_TS
ELSE TS_MASK.TS_MASK_TS
END AS MODIFY_TS
FROM (
SELECT COUNT(*) AS count
FROM _V_USERGROUPS
WHERE USERNAME IN (
SELECT SESSION_USERNAME
FROM _V_SESSION_DETAIL
WHERE SESSION_ID = current_sid
)
AND GROUPNAME = 'GROUP_AUTH2READ'
) SECURITY_GRP_CNT
,ADMIN.PI_HRCHY
,CHAR_MASK
,NUM_MASK
,TS_MASK
WHERE (
(PI_HRCHY.HRCHY_TYP_ID = 11)
AND (PI_HRCHY.ACTV_IND = 'Y'::"NCHAR")
);
The solution NzGuy provided solved my problem. As he stated, apparently placing the current_sid contact in the WITH clause of the SQL causes the constant to be evaluated differently than if it were placed outside the WITH. The common table expression defined outside the WITH clause resolved my problem.

IF Statement in a calculated field (SSAS Tabular)

I'm in the process of creating a tabular model cube in SSAS and I've become a bit stuck on some of my measures for the calculated columns
I have already converted this case statement to an IF in SSAS
case when PROPERTY_CHARGE.PCH_CURRENT_IND='Y' then PROPERTY_CHARGE.PCH_AMT else 0 end
is now
=If ([PCH_CURRENT_IND]="Y", [PCH_AMT],0)
I'm now struggling to convert this one:
sum(case when PROPERTY_CHARGE.PCH_CURRENT_IND='N' and PROPERTY_CHARGE.PCH_END_DATE is null then PROPERTY_CHARGE.PCH_AMT else 0 end
I've tried various arrangements but no matter what i'm getting errors either related to is null or AND not being available in this context or other errors advising I have too many arguments.
Can anyone assist please?
IN tabular is very different the logic, you can create a measure like this :
MeasureName:=CALCULATE(sum([PCH_AMT]),FILTER(PROPERTY_CHARGE,[PCH_CURRENT_IND]="N"&&[PCH_END_DATE]=BLANK()))
ANd give you the same result of case
use:
=If ([PCH_CURRENT_IND]="Y", [PCH_AMT],BLANK())
and then :
MeasureName:
=CALCULATE(sum([PCH_AMT]),FILTER(PROPERTY_CHARGE,[PCH_CURRENT_IND]="N"&&[PCH_END_DATE]=BLANK()))
that is the same as the case
This solution will be a little more performant than the previous posts and a little easier to read, use this for a Measure:
Strruggling To Convert measure:=
CALCULATE (
SUM ( 'PROPERTY_CHARGE'[PCH_AMT] ),
FILTER (
ALL ( 'PROPERTY_CHARGE'[PCH_CURRENT_IND], 'PROPERTY_CHARGE'[PCH_END_DATE] ),
AND (
'PROPERTY_CHARGE'[PCH_CURRENT_IND] = "N",
ISBLANK ( 'PROPERTY_CHARGE'[PCH_END_DATE] )
)
)
)
Struggling To Convert Calculate column :=
SWITCH (
TRUE (),
AND (
'PROPERTY_CHARGE'[PCH_CURRENT_IND] = "N",
ISBLANK ( 'PROPERTY_CHARGE'[PCH_END_DATE] )
), SUM ( 'PROPERTY_CHARGE'[PCH_AMT] )
)

How to make Linq to SQL translate to a derived column?

I have a table with a 'Wav' column that is of type 'VARBINARY(max)' (storing a wav file) and would like to be able to check if there is a wav from Linq to SQL.
My first approach was to do the following in Linq:
var result = from row in dc.Table
select new { NoWav = row.Wav != null };
The problem with the code above is it will retreive all the binary content to RAM, and this isn't good (slow and memory hungry).
Any idea how to have Linq query to translate into something like bellow in SQL?
SELECT (CASE WHEN Wav IS NULL THEN 1 ELSE 0 END) As NoWav FROM [Update]
Thanks for all the replies. They all make sense. Indeed, Linq should translate the != null correctly, but it didn't seem to effectively do it: running my code was very slow, so somehow my only explaination is that it got the binary data transfered over to the RAM.... but maybe I'm wrong.
I think I found a work around anyway somewhere else on stackoverflow: Create a computed column on a datetime
I ran the following query against my table:
ALTER TABLE [Table]
ADD WavIsNull AS (CASE WHEN [Wav] IS NULL Then (1) ELSE (0) END)
Now I'll update my DBML to reflect that computed column and see how it goes.
Are you sure that this code will retrieve the data to RAM?
I did some testing using LINQPad and the generated SQL was optimized as you suggest:
from c in Categories
select new
{
Description = c.Description != null
}
SELECT
(CASE
WHEN [t0].[description] IS NOT NULL THEN 1
ELSE 0
END) AS [Description]
FROM [Category] AS [t0]
What about this query:
var result = from row in dc.Table where row.Wav == null
select row.PrimaryKey
for a list of keys where your value is null. For listing of null/not null you could do this:
var result = from row in db.Table
select new
{ Key = row.Key, NoWav = (row.Wav == null ? true : false) };
That will generate SQL code similar to this:
SELECT [t0].[WavID] AS [Key],
(CASE
WHEN [t0].[Wav] IS NULL THEN 1
ELSE 0
END) AS [NoWav]
FROM [tblWave] AS [t0]
I'm not clear here, your SQL code is going to return a list of 1s and 0s from your database. Is that what you are looking for? If you have an ID for your record then you could just retrieve that single record with the a condition on the Wav field, null return would indicate no wav, i.e.
var result = from row in dc.Table
where (row.ID == id) && (row.Wav != null)
select new { row.Wav };