count by each status on max planid per emp in DAX - ssas

I need to create measure based on maxium planid per each emp. I tried dax query in ssas (SSMS) but not getting expected results.
Logic: We need to calculate count by each status on latest plan.
for example: employee (5245) is having two plans (8869,6988)
when we calculate status for accepted then we have to consider this empid becauase latest planid(8869) staus is accepted .i.e. this eid should consider status: ACCEPTED only because it has the latest planid.
Source Data
OutPut Expected
I am using below query
Define
MEASURE table[AcceptedCount] =
`
COUNTROWS (
FILTER (
SUMMARIZE ( table,table[EmployeeNumber],table[status]),
table[status] = "ACCEPTED"
))
MEASURE table[EscalatedCount] =
COUNTROWS (
FILTER (
SUMMARIZE ( table,table[EmployeeNumber],table[status]),
table[status] = "ESCALATED"
))
MEASURE table[overall] =
COUNTROWS (
FILTER (
SUMMARIZE ( table,table[EmployeeNumber],table[status]),
table[status] in {"ESCALATED","ACCEPTED"}
))
VAR status_count =
SUMMARIZECOLUMNS (
table[unit],
"AcceptedCount_status", table[AcceptedCount],
"EscalatedCount_status", table[EscalatedCount]
"Overallcount",table[overall]
)
evaluate status_count
Output for the above query : this is wrong results
enter image description here

Related

Applying advanced filter in Power BI DAX, from a different table

I have the following tables:
Episodes:
Clients:
My DAX calculation sums up [Days_epi] unique values, from Episodes tbl, grouping them by [ProgramID_epi], [EpisodeID_epi], [ClientID_epi].
So, the SUM of [Days_epi] = 3 + 5 + 31 + 8 + 15 + 20 + 10 = 92
Here is my working code for this:
DaysSUM =
CALCULATE (
SUMX (
SUMMARIZE (
'Episodes',
'Episodes'[EpisodeID_epi],
'Episodes'[ProgramID_epi],
'Episodes'[ClientID_epi],
'Episodes'[Days_epi]
),
'Episodes'[Days_epi]
),
FILTER (
'Episodes',
'Episodes'[Category_epi] = "Homeless"
)
)
I need to add two advanced filters to the calculation above:
Filter 1 should ONLY KEEP records in Episodes, if the records in the Clients have the difference between [DischDate_clnt] and [AdmDate_clnt] >= 365.
Filter 1 in SQL statement is
DATEDIFF(DAY, [AdmDate_clnt], [DischDate_clnt]) >= 365)
After that, Filter 2 should ONLY KEEP records in Episodes, if the records in the Clients have
[Date_clnt] >= [AdmDate_clnt] + 12 months. (12 month after the Admission Date)
Filter 2 in SQL statement is
[Date_clnt] <= DATEADD(MONTH, 12, [[AdmDate_clnt])
So, after applying those two filters I expect the records 6 and 10 of the Episodes tbl must be excluded (filtered out), because the records 2 and 3 of the Clients tbl (highlighted in green) are not satisfied my Filter 1 / Filter 2.
Here is the final Episodes dataset I should have (without the 2 records in red):
I was starting to update my DAX code as the following (below).
But keep receiving error "Parameter is not the correct type"
enter
DaysSUM_Filters =
CALCULATE (
SUMX (
SUMMARIZE (
'Episodes',
'Episodes'[EpisodeID_epi],
'Episodes'[ProgramID_epi],
'Episodes'[ClientID_epi],
'Episodes'[Days_epi]
),
'Episodes'[Days_epi]
),
FILTER (
'Episodes',
'Episodes'[Category_epi] = "Homeless"
), TREATAS(DATEDIFF('Clients'[AdmDate_clnt],
'Clients'[DischDate_clnt], DAY)>=365,
'Clients'[Date_clnt])
)
Not exactly sure how to set those 2 filters correctly in DAX Power BI, as I
am relatively new to it.
Please help!
I can't say about all the case. But what is obvious is that you use TREATAS in a wrong way. It works like this TREATAS({"Red", "White", "Blue"}, 'Product'[Color]).
In your case
DATEDIFF('Clients'[AdmDate_clnt],
'Clients'[DischDate_clnt], DAY)>=365
will return TRUE or FALSE value. The first argument of TREATAS - is a column or set of columns not a single value.
You can use the filter like this:
FILTER(
'Clients'
,DATEDIFF(
'Clients'[AdmDate_clnt]
,'Clients'[DischDate_clnt]
,DAY
)>=365
)
This will return you a filtered table.
This may work if your tables are linked.

SQL Server: Generate squashed range data from daily dates by an id

Basically to sum up the goal. I want to generate something using the following data. Where it subtotals like excel where "each change in ... ordered however" generate summary records and only generate summary records and squash date ranges.
All I want are the count records would generate rows and would copy the fee data except for the begin/end fields would be the ranged dates. So first record would be fee 9858 from 3/31 - 4/14 for example. Each count row would be a new fee record.
I am not sure which combination of grouping, partition by.... and such to get what I need or if there is something else I can use. I can provide sql if needed but I am mainly looking for finding the right combination of tools(partition by, grouping, rollup....) that would provide this functionality.
WITH [ag]
AS (SELECT *,
LAG([Fee_ID]) OVER (ORDER BY [FeeTypeID], [FeeBeginDate]) [FirstFee],
LAG([Fee_ID]) OVER (ORDER BY [FeeTypeID], [FeeBeginDate] DESC) [LastFee]
FROM [dbo].[HHTFees]
WHERE [Retailer] = 517),
[agf]
AS (SELECT *,
'Beg' [FeeStopType]
FROM [ag]
WHERE [ag].[FirstFee] <> [ag].[Fee_ID]
OR [ag].[FirstFee] IS NULL),
[agl]
AS (SELECT *,
'End' [FeeStopType]
FROM [ag]
WHERE [ag].[LastFee] <> [ag].[Fee_ID]
OR [ag].[LastFee] IS NULL),
[results]
AS (SELECT *
FROM [agf]
UNION
SELECT *
FROM [agl]),
[indexed]
AS (SELECT *,
ROW_NUMBER() OVER (ORDER BY [results].[FeeTypeID], [results].[FeeBeginDate]) [RowNum]
FROM [results])
SELECT [Starts].[Retailer],
[Starts].[Chain_key],
[Starts].[Fee_ID],
[Starts].[FeeTypeID],
[Starts].[FeeChgTypeID],
[Starts].[Fee],
[Starts].[FeeDescription],
[Starts].[FeeTypeDescription],
[Starts].[FeeBeginDate],
[Ends].[FeeEndDate],
[Starts].[FeeAmt],
[Starts].[HHT_ID],
[Starts].[CreatedBy],
[Starts].[CreatedDate],
[Starts].[ModifiedBy],
[Starts].[ModifiedDate],
[Starts].[MsgID],
[Starts].[ScopeOrder],
[Starts].[Scope],
[Starts].[FirstFee],
[Starts].[LastFee],
[Starts].[FeeStopType],
[Starts].[RowNum]
FROM [indexed] [Starts]
INNER JOIN [indexed] [Ends]
ON [Starts].[Fee_ID] = [Ends].[Fee_ID]
AND [Ends].[RowNum] = [Starts].[RowNum] + 1;
I used lag to find where the fee id changed sorted by feetype / start date. This allowed me to mimic when fee id changed sorted by begin date like excel subtotal. Now to optimize and tweak to fit the set of data.

Get the item with the highest count

Can you please help me to get the item with the highest count using DAX?
Measure = FIRSTNONBLANK('Table1'[ItemName],CALCULATE(COUNT('Table2'[Instance])))
This shows the First ItemName in the table but doesnt get the ItemName of the Highest Value.
Thanks
Well, it's more complicated than I would have wanted, but here's what I came up with.
There things that you are hoping to do that are not so straightforward in DAX. First, you want an aggregated aggregation ;) -- in this case, the Max of a Count. The second thing is that you want to use a value from one column that you identify by what's in another column. That's row-based thinking and DAX prefers column-based thinking.
So, to do the aggregate of aggregates, we just have to slog through it. SUMMARIZE gives us counts of items. Max and Rank functions could help us find the biggest count, but wouldn't be so useful for getting Item Name. TOP N gives us the whole row where our count is the biggest.
But now we need to get our ItemName out of the row, so SELECTCOLUMNS lets us pick the field to work with. Finally, we really want a value not a 1-column, 1-row table. So FirstNonBlank finishes the job.
Hope it helps.
Here's my DAX
MostFrequentItem =
VAR SummaryTable = SUMMARIZE ( 'Table', 'Table'[ItemName], "CountsByItem", COUNT ( 'Table'[ItemName] ) )
VAR TopSummaryItemRow = TOPN(1, SummaryTable, [CountsByItem], DESC)
VAR TopItem = SELECTCOLUMNS (TopSummaryItemRow, "TopItemName", [ItemName])
RETURN FIRSTNONBLANK (TopItem, [TopItemName])
Here's the DAX without using variables (not tested, sorry. Should be close):
MostFrequentItem_2 =
FIRSTNONBLANK (
SELECTCOLUMNS (
TOPN (
1,
SUMMARIZE ( 'Table', 'Table'[ItemName], "Count", COUNT ( 'Table'[ItemName] ) ),
[Count], DESC
),
"ItemName", [ItemName]
),
[ItemName]
)
Here's the mock data:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcipNSspJTS/NVYrVIZ/nnFmUnJOKznRJzSlJxMlyzi9PSs3JAbODElMyizNQmLEA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Stuff = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Stuff", type text}}),
#"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"Stuff", "ItemName"}})
in
#"Renamed Columns"

how can i combine 2 tables and including if clause into one column

I am pretty new in using SQL and trying to combine 2 tables within APEX ( interactive grid), based on the salary and rate the information to be taken from table X ( which i managed), but i need within the same SQL statement based on the information from column Type, to bring within column percentage if clauses to create the information.
and also within the same SQL statement to have the total which would be (ratehourspercentage).
but it seems i just cant manager to combine so many codes into one correctly, i have tried different ways based on what i have found examples all over, but it seems it will just not work for some reason.
select
Overtime.ID,
OVERTIME.EMPLOYEE_NUMBER,
OVERTIME.EMPLOYEE_FULL_NAME,
OVERTIME."DATE",
OVERTIME.TYPE,
OVERTIME.HOURS,
EMPLOYEES.RATE,
EMPLOYEES.SALARY,
OVERTIME.PERCENTAGE (CASE
WHEN TYPE = "On Call " THEN "70%"
WHEN TYPE = "On Call PH" THEN "100%"
ELSE "150%"
END),
(Rate*hours*percentage) as total,
OVERTIME.CREATED,
OVERTIME.CREATED_BY
from OVERTIME
LEFT OUTER JOIN EMPLOYEES
ON OVERTIME.EMPLOYEE_NUMBER = EMPLOYEES.EMPLOYEE_NUMBER
group by Employee_Number
select
Overtime.ID,
OVERTIME.EMPLOYEE_NUMBER,
OVERTIME.EMPLOYEE_FULL_NAME,
OVERTIME."DATE",
OVERTIME.TYPE,
OVERTIME.HOURS,
EMPLOYEES.RATE,
EMPLOYEES.SALARY,
OVERTIME.PERCENTAGE,
(Rate*hours*percentage) as total,
OVERTIME.CREATED,
OVERTIME.CREATED_BY
from OVERTIME
LEFT OUTER JOIN EMPLOYEES
ON OVERTIME.EMPLOYEE_NUMBER = EMPLOYEES.EMPLOYEE_NUMBER
WHERE OVERTIME.TYPE LIKE
(CASE
WHEN TYPE = "On Call " THEN "70%"
WHEN TYPE = "On Call PH" THEN "100%"
ELSE "150%"
END);
group by Employee_number
The table for Overtime has the below:
ID Number primary Key
Employee_number vchar2
employee_full_name vchar2
date date
type vchar2
hours
salary number
rate number
percentage vachar2
total number
created timestamp
created_by vchar2
for the Employees table
ID number primary key
Employee_number vchar2
employee_full_name vchar2
salary number
rate number
i need to have the percentage information to reflect within the percentage column which i presume should be with if clause
You could calculate the total within the select statement using an SQL CASE statement.
Not sure that is the correct way to calculate the Total Pay - as you will want to Add the Basic Hourly rate to the % rate, but you can change that.
select
Overtime.ID,
OVERTIME.EMPLOYEE_NUMBER,
OVERTIME.EMPLOYEE_FULL_NAME,
OVERTIME."DATE",
OVERTIME.TYPE,
OVERTIME.HOURS,
EMPLOYEES.RATE,
EMPLOYEES.SALARY
,[Percentage] = CASE WHEN [Type] ='On Call ' THEN '70%'
WHEN [Type] = 'On Call PH' THEN '100%'
ELSE '150%'
END
,Total = CASE WHEN [Type] = 'On Call ' THEN (EMPLOYEES.RATE * OVERTIME.HOURS * 0.7)
WHEN [TYPE] = 'On Call PH THEN' THEN (EMPLOYEES.RATE * OVERTIME.HOURS)
ELSE (EMPLOYEES.RATE * OVERTIME.HOURS * 1.5)
END
,OVERTIME.CREATED
,OVERTIME.CREATED_BY
from OVERTIME LEFT OUTER JOIN EMPLOYEES ON OVERTIME.EMPLOYEE_NUMBER = EMPLOYEES.EMPLOYEE_NUMBER
group by Employee_Number

MDX Filtering dimension members with result of other dimension

I would like to filter a dimension for cube security with some information that are in another dimension.
So - I have a dimension which holds some account Responsible (Account Number and the initials on the one responsible) and another Dimension with all accounts.
I would like to make sure, that a person only can see movements on the accounts on which they are responsible.
I can make the filtering work like this:
SELECT
{} ON 0
,{
Exists
(
Filter
(
[Accounts].[Accounts].[AccountNo]
*
[AccountResponsible].[AccountResponsible].[AccountNo]
,
[Accounts].[Accounts].Properties("key")
=
[AccountResponsible].[AccountResponsible].Properties("key")
)
,[AccountResponsible].[Responsible].&[MSA]
)
} ON 1
FROM mycube;
the problem is, that there are two columns, and I can't use that in cube security. Is there a way to rewrite this, so that I actually get only one column with the members that the user are allowed to see?
Try using the Extract function:
SELECT
{} ON 0
,
EXTRACT(
{
Exists
(
Filter
(
[Accounts].[Accounts].[AccountNo]
*
[AccountResponsible].[AccountResponsible].[AccountNo]
,
[Accounts].[Accounts].Properties("key")
=
[AccountResponsible].[AccountResponsible].Properties("key")
)
,[AccountResponsible].[Responsible].&[MSA]
)
}
,[Accounts].[Accounts] //<<HIERARCHY YOU WISH TO EXTRACT
) ON 1
FROM mycube;