Count number times an observation appears connected to another column. DAX - dax

I'm working in a data set that tracks ownership of firms in a database. I have three databases. One with all the firms, one with all unique owners and one database with the relations between the owners and the firms. Each owner can own multiple firms. I want a calculated column that for each firm shows how many firms the specific owner or owners has. I have no idea how to do it.
It is something like; for each firm, search how many times the owner or owners appears in the relationship database and sum those to give a number for each firm.

After all data is in data model and relationships are created, calculated column in table Firms should look like this:
CountFirmsOfOwner = COUNTROWS(FILTER(Firms, Firms[OwnerID] = EARLIER(Firms[OwnerID])))

Related

Get aggregated information as part of an Eloquent many-to-many relationship

I am new to Laravel and need some help with what might be a basic question.
Race horses (can) have many owners. Owners (can) have many race horses. However, owners can buy and sell shares in race horses. At any point in time it must be possible to determine the share holding of each race horse.
My pivot table is defined as follows:
Schema::create('horse_owner', function (Blueprint $table) {
$table->id();
$table->foreignId ('horse_id');
$table->foreignId ('owner_id');
$table->date ('effective'); // the date when the transaction occurred
$table->integer ('shares')->default (1); // the number of shares + or -
$table->timestamps();
});
My Horse model includes a withPivot for effective and shares and I can show these in the Horses view. However, where an owner buys and sells shares, I would like the resultant number of shares to be shown.
The SQL query to find the current owners of a horse on a certain date looks like this:
SELECT `owners`.*, SUM(`horse_owner`.`shares`) AS `share_total`
FROM `owners`
INNER JOIN `horse_owner` ON `owners`.`id` = `horse_owner`.`owner_id`
WHERE `horse_owner`.`horse_id` = ? -- some horse
AND `horse_owner`.`effective` <= ? -- some date
GROUP BY horse_owner.owner_id;
While seeing the individual "transactions" is a necessary function, this share total will be mostly more useful than the individual transactions (e.g. summary reports, billing) and so being able to extract it easily for one or more horses or owners will be useful.
How does one set this up in Laravel and are there any best practice suggestions?
EDIT:
Based on other solutions, I've attempted the following:
return $this->belongsToMany (Owner::class)
->selectRaw ("`owners`.*, SUM(`horse_owner`.`shares`) AS `share_total`")
->withTimestamps()
->groupBy ("horse_owner.owner_id");
However, this results in an error because the query still includes "contains nonaggregated column horse_owner.id which is not functionally dependent on columns in GROUP BY clause".

Pivot two objects of same table in laravel

Assume the following two tables (stripped down to this question, assume there is more data on both):
user
id
user_similarity
user_1_id
user_2_id
similarity
I'd like to use user_similarity as a pivot table to construct a list of users that are similar to a given user.
To avoid storing duplicate data on the pivot table, I'd only like one record per user pair, with the lower user ID being stored in the first, and the higher ID in the second column.
Is it possible to set this up without duplicate data records and only a single eloquent relation?

Database: Storing multiple Types in single table or multiple intermediate tables for Delta Tables

Using Java and Oracle.
We need to update changes in Email, UserID of employee to third party.
Actual table is Employee and intermediate table we keep which we will use for comparison of changes before sending to third party.
Following are database designs coming in mind for intermediate table:
Only Single table:
EmployeeiD|Value|Type|UpdateDate
Value is userid or email, type will be 'email' or 'userid'. Update date is kept so to figure out that which of email or userid was different and update to third party.
Multiple Table:
Employee_EmailID
EmpId|EmailID|Updatedate
Employee_UserID
EmpId|UserID|Updatedate
Java flow will be:
Pick employee from actual table.
Pick employee from above intermediate table.
Compare differences. Update difference to third party.
Update above table with updated value and last update date.
Which one is consider as best way, single table approach or multiple table or is there any standard way to implement the same? There are 10,000 Employees in system.
Intermediate table is just storing Delta records i.e Records transferred to third party so that it can be compared next day.
Good database design has separate tables for different concepts. Using the same database column to hold different types of data will lead to code which is harder to understand, prone to data corruption and less performative.
You may think it's only two tables and a few tens of thousands of rows, so does it matter? But that is only your current requirement. What you choose now will set the template for what happens when (say) you need to add telephone numbers to the process.
Now in future if we get 5 more entities to update
Do you mean "entities", like say Customers rather than Employees? Or do you really mean "attributes" as in my example of Employee Telephone Number?
Generally speaking we have a separate table for distinct entities, and all the attributes of that entity are grouped at the same cardinality. To take your example, I would expect an Employee to have one UserID and one Email Address so I would design the table like this:
Employee_audit
EmpId|UserID|EmailID|Updatedate
That is, I have one record which stores the complete state of the Employee record at the Updatedate.
If we add a new entity, Customers then we have a new table. Simple. But a new attribute like Employee Phone Number offers a choice, because an employee can have more than one: work landline, mobile, fax, home, etc. So we could represent this in three ways: a child table with a type column, multiple child tables for each type, or as distinct columns on the Employee record.
For the main Employee table I would choose the separate table (or tables, depending on whether I'm shooting for 6NF). But for an audit table I would choose one record per Employee and pivot the phone numbers like this:
Employee_audit
EmpId|UserID|EmailID|Landline|Mobile|Fax|Home|Updatedate
The one thing I would never do is have a single table with type and value columns. It seems attractive because it means we could track additional entities without any further DDL. But in fact it becomes harder to re-assemble the complete state of an Employee at any given time with each attribute we add. Also it means the auditing process itself is more complicated (because it needs to determine which attributes have changed and whether it needs to audit the change) and more expensive (because changing three attributes on the same record entails inserting three audit records).

USERELATIONSHIP in a measure with text column

CONTEXT:
I want to monitor payment transactions for money laundering, where payments cross multiple borders. There are a max of 6 countries shown per transaction. For each of these countries, I need to know a risk level.
I have 2 tables:
Transaction data (where there are many transactions from same country)
Country Risk (containing each country once, with an added risk classification. There are 100+ countries, and only 6 different Risk levels).
Problem:
I would like to look up the Risk Classification per country in Transaction Data. The problem is, there are 6 countries per transaction in Transaction Data. So I have to link Transaction data to Country Risk 6 times. Only 1 relationship can be active, of course.
So I tried writing the following measure:
CALCULATE(
VALUES('Country Risk'[Risk classification]);
USERELATIONSHIP('Transaction Data'[Country 2];'Country Risk'[Country Code]))
I get an error though when using the measure in a graph where I listed the countries from Transaction Data (where every country is mentioned in multiple rows) and I wanted to see the related risk categories:
A table of multiple values was supplied where a single value was expected
What am I doing wrong?
Made similar test data: https://drive.google.com/file/d/1_kJW-BpbrwCsbSpxdo7AJ3IzPy2oLWFJ/view?usp=sharing
Needed:
for every C (C1-C6) column I need to add the risk category.
For every C column I need to make a pie chart showing the number of transactions per risk category for that C column
Pie charts should filter the transaction oevrview: (
I've taked a PBI consultant about this, there is no way to get this issue solved the way I want it to (to have multiple relationships between 2 tables all acting as if they were active relationships at same time).
the only way of getting it done would be:
1. write measures (but that doesn't allow cross filtering between pie chart and table below)
2. unpivot the country columns (but that wouldn't allow to have 6 columns with risk category in table)
3. have 6 dimension tables (this solves the issue, because it allows both cross filtering between piechart and other piecharts & table. and it would allow to have 6 columns for separate risks in the table visual)
thanks for trying to help guys!

Laravel eloquent for non-related tables

I have tables as seen here
An Athlete has many test days (e.g. one for each year), an Institution has teams e.g. Redham High School Rugby U14 Level. The team table is composed of the Institution, a sport and a level. Sport and Level are maintained in Codelist, which is just a table to maintain entities that are not big enough to be a table. Almost like replacing the hard coding of droplists.
Question 1: I don't see that the Codelist is related to the Team table, since Code list store unrelated info as well, like Country names, province names etc. Example of Codelist data below. Should they be related?
Question 2:
When creating a Test day record, I need the user to select for which team this athlete is getting tested for. I'm getting the Team records, but how do I now access the sport and level names from the Codelist?
I can't do $team->sport->name as they're not related tables.
Below is my current code. How do I get user friendly values for sportcode and levelcode e.g. Rugby U14.
$teams = Team::whereHas('Institution', function($query){
$query->whereClient_id(1);
})->get();
I can with $teams loop get the sportcode and level code and now write separate queries to fetch the names from the codelist. This would send 3 collections back to the view and doesn't seem the eloquent way. Advice appreciated.

Resources