How to make formula field for salesforce field? - if-statement

I am trying to make formula field for the salesforce field. the condition is given below.
if Company = "WIL" And (ShippingCountry = "United States" Or "USA") then
"US"
elseif Company = "WST" And (ShippingCountry = "United States" Or "US") then
"USA"
elseif ShippingCountry <> "" then
ShippingCountry
elseif Company = "WIL" then
"US"
elseif Company = "WST" then
"USA"
else
""
end if

The trailheads are always a good start. I would suggest Use Formula Fields and Advanced Formulas.
The documentation pages about Formula Operators and Functions might be useful too.
Keep in mind that you must use fields API Names, not labels, so it's Company__c.
If Company__c is not a picklist field:
IF( AND(Company__c = 'WIL', OR(ShippingCountry = 'United States', ShippingCountry = 'USA')),
'US',
IF( AND(Company__c = 'WST', OR(ShippingCountry = 'United States', ShippingCountry = 'US')),
'USA',
IF( NOT( ISBLANK(ShippingCountry) ),
ShippingCountry,
IF( Company__c = 'WIL',
'US',
IF(Company__c = 'WST', 'USA', '')
)
)
)
)
If Company__c is a picklist field you should use ISPICKVAL(picklist_field, literal_value), so the formula would be:
IF( AND( ISPICKVAL(Company__c, 'WIL'), OR(ShippingCountry = 'United States', ShippingCountry = 'USA')),
'US',
IF( AND(ISPICKVAL(Company__c, 'WST'), OR(ShippingCountry = 'United States', ShippingCountry = 'US')),
'USA',
IF( NOT( ISBLANK(ShippingCountry) ),
ShippingCountry,
IF( ISPICKVAL(Company__c, 'WIL'),
'US',
IF( ISPICKVAL(Company__c, 'WST'), 'USA', '')
)
)
)
)

Related

Doctrine: Automatic ResultMapping of Native Query?

After some research, I made this UNION query work in my Repository class:
class PostRepository extends ServiceEntityRepository {
// ...
public function getLatestPostsOfUser ($limit = 10) : ?array {
$sql = <<<SQL
SELECT p.id, p.title, p.content, p.images, p.parent_id, p.parent_type, p.created, p.last_modified FROM cms_posts p
LEFT JOIN cms_user_follow ON (p.parent_type = cms_user_follow.followed_entity_type AND p.parent_id = cms_user_follow.followed_entity_id)
WHERE cms_user_follow.user_id = {$this->currentUser->getId()}
UNION
SELECT p.id, p.title, p.content, p.images, p.parent_id, p.parent_type, p.created, p.last_modified FROM cms_posts p
LEFT JOIN project_memberships ON (p.parent_type = 'Project' AND p.parent_id = project_memberships.project_id)
WHERE project_memberships.user_id = {$this->currentUser->getId()} and project_memberships.status = 1
ORDER BY created DESC
LIMIT $limit
SQL;
$res = [];
try {
$rsm = (new ResultSetMapping())
->addEntityResult(Post::class, 'p')
->addFieldResult('p', 'id', 'id')
->addFieldResult('p', 'title', 'title')
->addFieldResult('p', 'content', 'content')
->addFieldResult('p', 'images', 'images')
->addFieldResult('p', 'parent_id', 'parentId')
->addFieldResult('p', 'parent_type', 'parentType')
->addFieldResult('p', 'created', 'created')
->addFieldResult('p', 'last_modified', 'lastModified')
;
$res = $this->getEntityManager()->createNativeQuery($sql, $rsm)->getArrayResult();
} catch (DBALException $e) {
}
return $res;
}
}
It involves an awefull lot of manual field mapping, so I was wondering wheather there is an automatic solution to this?
Many thx!
It looks like Doctrine can do something like this under the hood and also apply the mappings automatically:
$qb = $this->em->createQueryBuilder();
$where = $qb->expr()->andX(
$qb->expr()->eq('f.followedEntityId', ':parentId'),
$qb->expr()->eq('f.followedEntityType', ':parentType'),
$qb->expr()->eq('f.following', 1),
$qb->expr()->eq('u.allowEmailNotifications', 1),
$qb->expr()->eq('u.enabled', 1),
);
$qb->select('f', 'u')
->from(UserFollow::class, 'f')
->leftJoin(
User::class,
'u',
Join::WITH,
'f.userId = u.id'
)
->where($where)
->setParameters([
'parentId' => $post->getParentId(),
'parentType' => $post->getParentType()
])
;
$usersAndFollowings = $qb->getQuery()->getResult();
$usersAndFollowings is then a flat array with both entities alternating: [UserFollow, User, UserFollow, User, ...]
You'll probably want to process it afterwards, so that connected UserFollow and User entities are together in a sub array.

PowerBI Conditional Column with multiple different conditions

I am looking to created a new column in my dataset based on some other fields. I want to use this then as a filter for my visuals.
I have created a switch formula for 95% of my customers fall into. I have a few exceptions and I am wondering how I could cater for them.
Eg:
VAR _1 = IF ('Table'[Customer ID] = "Customer 1011" && 'Table'[ITEM Cat] <> "House", "USA" , "EUROPE')
VAR _2 = IF('Table'[Customer ID] = "Customer 1013" && 'Table'[OrderDate] < "2021/07/01", "Europe", "USA")
This is the switch code so far I have:
PostalCode = SWITCH([Customer ID] ,
"Customer 1001" , "USA",
"Customer 1002" ,"EU",
"Customer 1003" , "ASIA",
Any feedback would be greatly appreciated :)
Use switch this way:
YourColumn = SWITCH(
TRUE(),
'Table'[Customer ID] = "Customer 1011" && 'Table'[ITEM Cat] <> "House", "USA",
'Table'[Customer ID] = "Customer 1013" && 'Table'[OrderDate] < "2021/07/01", "Europe",
"ELSEHERE"
)
https://dax.guide/switch/

filter the new table by range of data, e.g. 1997-2020 PowerBI

Error:The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value.
I intend to select Data by datecolumns from 1997 to 2020. But no success
New Periode =
VAR DateStart =
DATE ( "1997", "1", "1" )
VAR DateEnd =
DATE ( "2021", "11", "10" )
RETURN
CALCULATETABLE (
'Date_data',
FILTER ( 'Date_data', 'Date_data'[Date] <= DateEnd && 'Date_data'[Date] >= DateStart )
)
Can you please try this below code-
Periode =
VAR DateStart = DATE ( "1997", "1", "1" )
VAR DateEnd = DATE ( "2021", "11", "10" )
RETURN
CALCULATETABLE (
'Date_data',
'Date_data'[Date] <= DateEnd
&& 'Date_data'[Date] >= DateStart
)

Power BI, DAX, Many-to-one and relational tables

I previously asked a question here:
DAX subquery measure?
for instruction on how to create a specific measure column for a visualisation. To keep the example simple, I kept it to one fictitious table and the DAX query worked really well.
In reality, however, the visualisation that the measure column is for is made up of multiple joined tables. And the results of the DAX query unexpectedly produced all zeros! So I'll refactor my example here for more help...
Requirement
I want a count of how many 'Apps' are not equal to 'Complete' for a specific 'Build'.
Data Model
Builds
Build
App
Apps
App
Status
Sample Data
Builds
Build...........App
Build1..........App1
Build1..........App2
Build1..........App9
Build2..........App3
Build3..........App1
Build3..........App5
Build3..........App8
Build3..........App9
Apps
App...........Status
App1..........UAT
App2..........Complete
App9..........New
App3..........Complete
App5..........UAT
App8..........Complete
Relationship
The relationship is MANY Builds.App to ONE Apps.App.
Visualisation Table
This is my visualisation - note the different tables:
Builds.Build....Builds.App....Apps.Status
Build1..........App1..........UAT
Build1..........App2..........Complete
Build1..........App9..........New
Build2..........App3..........Complete
Build3..........App1..........UAT
Build3..........App5..........UAT
Build3..........App8..........Complete
Build3..........App9..........New
This is my required results:
Builds.Build....Builds.App....Apps.Status....AppsNotCompleteForBuild
Build1..........App1..........UAT............2
Build1..........App2..........Complete.......2
Build1..........App9..........New............2
Build2..........App3..........Complete.......0
Build3..........App1..........UAT............3
Build3..........App5..........UAT............3
Build3..........App8..........Complete.......3
Build3..........App9..........New............3
ATTEMPT 1 (Not working!)
CALCULATE (
COUNT ( Builds[App] ),
FILTER (
ALL ( Builds[Build], Builds[App] ),
Builds[Build] = SELECTEDVALUE ( Builds[Build] )
),
FILTER (
ALL ( Apps[Status] ),
Apps[Status] <> "Complete"
)
) + 0
ATTEMPT 2 (Not working!)
Measure 5 = CALCULATE (
COUNT ( Builds[App] ),
FILTER (
ALL ( Builds[Build] ),
Builds[Build] = SELECTEDVALUE ( Builds[Build] )
),
FILTER (RELATEDTABLE(Apps),
Apps[Status] <> "Complete")
) + 0
ATTEMPT 3 (Not working!)
Measure5 = CALCULATE (
COUNTAX(FILTER( Builds
, RELATED(Apps[Status]) <>"Complete"
&& Builds[Build] = SELECTEDVALUE(Builds[Build])
)
,Builds[App])
) + 0
using these tables with a many to one relationship between Builds and Apps
Builds =
DATATABLE(
"Build", STRING,
"App", STRING,
{
{ "Build1", "App1" },
{ "Build1", "App2" },
{ "Build1", "App9" },
{ "Build2", "App3" },
{ "Build3", "App1" },
{ "Build3", "App5" },
{ "Build3", "App8" },
{ "Build3", "App9" }
}
)
Apps =
DATATABLE(
"App", STRING,
"Status", STRING,
{
{ "App1", "UAT" },
{ "App2", "Complete" },
{ "App9", "New" },
{ "App3", "Complete" },
{ "App5", "UAT" },
{ "App8", "Complete" }
}
)
we can write a dax measure that counts the number of apps per build that are not in "Complete" status. Since an app can have just one status, otherwise the many to one relationship would break, it's enough to filter out status = "Complete" when counting.
# not complete =
IF(
HASONEVALUE( Builds[Build] ),
VAR CurrentBuild =
SELECTEDVALUE( Builds[Build] )
RETURN
COUNTROWS(
FILTER(
ALL( Builds ),
Builds[Build] = CurrentBuild
&& RELATED( Apps[Status] ) <> "Complete"
)
) + 0
)
With this formula we can use a Table Visual to get this result
Edit: this will also handle cases where there are missing Apps in Apps table, just ignoring them
# not complete =
IF(
HASONEVALUE( Builds[Build] ),
VAR CurrentBuild =
SELECTEDVALUE( Builds[Build] )
VAR CurrentApp =
SELECTEDVALUE( Apps[App] )
VAR Result =
COUNTROWS(
FILTER(
ALLNOBLANKROW( Builds ),
Builds[Build] = CurrentBuild
&& RELATED( Apps[Status] ) <> "Complete"
&& NOT ISBLANK( RELATED( Apps[Status] ) )
)
) + 0
RETURN
IF( NOT ISBLANK( SELECTEDVALUE( Apps[Status] ) ), Result )
)

In Power BI, is it possible to hold a column in a Measure variable?

We have a slicer with the value "Local" and "USD".
Depending on the selection we want to use a different column of data for calculations.
This works.
Billings Sum =
IF(
SELECTEDVALUE(CurrencyPickerTable[Currency]) = "Local",
SUM('BillingsTable'[Billings (local)]),
SUM('BillingsTable'[Billings (USD)])
)
However, it's going to get more complicated because we want to also add a slicer for "Fiscal Year" and "Calendar Year" year.
If both possible selections are in the RETURN section there will be a bunch of repeated code.
Is it possible to put a column into a variable and use it later in the calculation?
This is my failing attempt.
Billings Sum =
var selectedCurrencyColumn =
IF(
SELECTEDVALUE(CurrencyPickerTable[Currency]) = "Local",
SELECTCOLUMNS(BillingsTable, "local", [Billings (local)]),
SELECTCOLUMNS(BillingsTable, "USD", [Billings (USD)])
)
RETURN
SUM(selectedCurrencyColumn)
How can I get a column into the currencyColumn variable?
What you are trying to do is not possible afaik, but you might obtain a nice formula using the SWITCH TRUE method and some variables to check the selection
[Billings Sum] =
VAR CurrencySelection =
SELECTEDVALUE ( CurrencyPickerTable[Currency] )
VAR CalendarSelection =
SELECTEDVALUE ( CalendarPickerTable[Calendar] )
RETURN
SWITCH (
TRUE (),
CurrencySelection = "Local"
&& CalendarSelection = "Calendar Year", [Billings (local)],
CurrencySelection = "Local"
&& CalendarSelection = "Fiscal Year", [Billings (local) FC],
CurrencySelection = "USD"
&& CalendarSelection = "Calendar Year", [Billings (USD)],
CurrencySelection = "USD"
&& CalendarSelection = "Fiscal Year", [Billings (USD) FC],
BLANK ()
)
This assumes that you have a measure to cover each possible combination of the selections matrix (Currency and Calendar in this case), but if that's not the case you can also create some variables as measures or write the formula inside the switch.
Reference:
https://www.sqlbi.com/articles/optimizing-if-and-switch-expressions-using-variables/