Addition and Subtraction with Query Builder Doctrine ORM 2 - doctrine-orm

I have a transaction table with a list of transactions (deposits) made by my users.
ID | user_id | credit | debit | status
1 | 1 |5 |1
2 | 1 |12 |1
3 | 1 |8 |1
To figure out the current balance of each user, I need to take the sum of all the credits and subtract the sum of all the debits.
The MySql statement would be something like this:
SELECT SUM(Credit) - SUM(Debit) as Balance FROM Transactions WHERE user_id = 1 ANS status = 1;
How would this be done in QB?

This was relatively simple to solve, here is my final function that returns my users account balance using DQL:
public function getUserBalance($userObject)
{
return $this->transactionRepository->createQueryBuilder('u')
->add('select','SUM(u.credit) - SUM(u.debit)')
->where('u.status = :status')
->andWhere('u.user = :userObject')
->setParameter('status' , 1)
->setParameter('userObject' , $userObject)
->getQuery()
->getSingleScalarResult();
}

Related

How to generate rank in Power BI on the basis of two column

I am new to Power BI and need some help regarding the Power BI RANKX function
So the scenario is I have Emp name and emp_id fields in my employee table and I have the office_distance and emp id column from the office table.
I want to create a column in my visual which contains ranking on the distance and name basis.
Example:
| EmpName | off_dist | Rank |
|-------- |----------|------|
| A | 10 | 1 |
| A | 20 | 2 |
| A | 30 | 3 |
| B | 20 | 3 |
| B | 10 | 1 |
| B | 15 | 2 |
Please let me know how can I achieve this
Please refer to below DAX formulas for calculated columns. And if this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Create a column to rank by the Employee Name
Rank EName = RANKX(ALL(Table), U381[Table], ,ASC, Dense)
Create another column to rank by Employee Name and by the Office Distance.
Ranking on EName and Distance =
VAR X = MAX('Table'[Rank E_Name])
var result =
RANKX(
ALL(Table),
Table[O_Distance] * X + Table[Rank E_Name], ,
ASC
)
RETURN
result

Get count and list of cutomers (ID) that have no sales in the last 2 months

So, I've 2 tables as under
SALES table:
+----+------------+
| ID | SALE_DATE |
+----+------------+
| 1 | 09-21-2021 |
| 2 | 09-21-2021 |
| 3 | 09-21-2021 |
| 2 | 09-21-2021 |
| 3 | 09-21-2021 |
| 1 | 09-21-2021 |
| 5 | 07-22-2021 |
| 6 | 09-21-2021 |
| 9 | 09-21-2021 |
| 7 | 08-21-2021 |
| 8 | 05-21-2021 |
+----+------------+
CUSTOMER Table
+----+
| ID |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+----+
I want to create 2 measures:
1st would be the count of customers that have no sales in the last 2 months, so in this case it would be 2 (8 and 10)
and second measure would give the list of all those customer ID's (8 and 10)
Right now I use this measure to get the list of all ID's that have no sales in last 2 months
show_hide =
VAR current_name = MIN(SALES[ID])
VAR chk_not_in =
IF(
COUNTROWS(
FILTER(
ALL(SALES),
SALES[ID]= current_name && SALES[SALE_DATE])> DATE(YEAR(NOW()),MONTH(NOW())-2, DAY(NOW()))
)
)= 0,
0,
1
)
VAR chk_in =
IF(
COUNTROWS(
FILTER(
ALL(CUSTOMER),
CUSTOMER[ID] = current_name
)
) = 0,
0,
1
)
RETURN IF(chk_in = 1 && chk_not_in = 1, 1, 0)
So every ID with a show_hide of "0" would be the ones that dont have any sales in the last 2 months
I was wondering if there's an easy way to do it and also, I'm not sure how to get the count of all those ID's
First off - I assume your test data was meant to be 2020 instead of 2021 and the ID in the SALES table is a CUSTOMER ID.
I would address this as a measure and a calculated column.
The measure would calculate the customers that have not sold in the past two months. From your data I think you are missing (4) who has not sold anything - bringing the total customers to three (4, 8, 10).
CustomersWithNoSalesIn2Months =
// Work out what date was 2 months ago
VAR twoMonthsAgo = DATE(YEAR(NOW()),MONTH(NOW())-2, DAY(NOW()))
// Count the total distinct customers in the customer table
VAR totalCustomers = CALCULATE(DISTINCTCOUNT(Customer[ID]))
// Count how many distinct customers did have sales in the past 2 months
VAR customersWithSalesInTheLast2Months = CALCULATE(DISTINCTCOUNT(Sales[ID]), Sales[SALE_DATE] > twoMonthsAgo)
// Subtract the customers who did have sales from the total to get the number of customers that did not have sales
RETURN totalCustomers - customersWithSalesInTheLast2Months
The calculated column would be places on the CUSTOMER table and would count how many sales customers had made in the last 2 months.
SalesMadeInTheLast2Months =
VAR MostRecentSale = CALCULATE(MAX(Sales[SALE_DATE]), FILTER(Sales, Customer[ID] = Sales[ID]))
VAR TwoMonthsAgo = DATE(YEAR(NOW()),MONTH(NOW())-2, DAY(NOW()))
RETURN CALCULATE(COUNTROWS(Sales), FILTER(Sales, Sales[SALE_DATE] > TwoMonthsAgo), FILTER(Sales, Sales[ID] = Customer[ID]))
Now you can filter on the Customers table for BLANK sales or use the counts in any other calculation you need. For example, customers 1,2 & 3 have made the most sales in the past 2 months.

django left join and right join implement sqlite

I have two tables as shown below :
country
id name
1 A
2 b
3 c
state
id | country_id | name | population
1 | 1 | x | 234354
2 | 1 | y | 2334
3 | 2 | h | 232323
4 | 2 | E | 8238787
Now I want query with sum population with country name like this :
a has xxxx population
b has xxxx population
c has 0 population
In django query, I have write this query :
City.objects.values('country__name').annotate(Sum('population'))
But this has not display 0 for c country :(
The query is not showing any record for c country, because table does not have any record for c country.
City.objects.values('country__name').annotate(Sum('population'))
This query will show any those records which are there in the City Model.

How to calculate inventory per day from movement table with Power BI DAX?

I have a table with inventory movements. Each inventory item has a unique ID and they change status overtime (let's say status A, B, C and D, but not always in this order). Each status change of an ID is a new record in the table with the timestamp of the status change. My goal is to calculate with Power BI DAX the number of inventory at a certain day in status 'B'. The logic is to count the number of distinct IDs, which breached status 'B' before the certain day but doesn't have any newer status before that day.
Example of the source table:
ID | TimeStamp | Status
1 | 8/20/2018 | A
1 | 8/21/2018 | B
1 | 8/24/2018 | C
2 | 8/19/2018 | A
2 | 8/20/2018 | B
2 | 8/22/2018 | C
2 | 8/24/2018 | D
3 | 8/18/2018 | A
3 | 8/21/2018 | B
4 | 8/15/2018 | A
4 | 8/17/2018 | B
4 | 8/24/2018 | D
Example of the output table:
Date | Count of Items in Status B on this Day
8/17/2018 | 3
8/18/2018 | 2
8/19/2018 | 0
8/20/2018 | 8
8/21/2018 | 10
8/22/2018 | 5
8/23/2018 | 3
I was thinking of creating a table for the latest timestamp with status 'B' for each ID and then look for the next timestamp, after the timestamp of status 'B', if applicable:
ID (primary key) | TimeStamp of 'B' breached | TimeStamp of next status breach
1 | 8/20/2018 | 8/21/2018
2 | 8/18/2018 | 8/22/2018
3 | 8/21/2018 |
4 | 8/15/2018 | 8/20/2018
Then I would plug the above data into the Date context and count the number of IDs from the above table, where the "TimeStamp of 'B' breached" value is smaller AND the "TimeStamp of next status breach" value is greater than the certain date.
Unfortunately I am not sure how to plug this logic into DAX syntax, hence any recommendations would be appreciated.
Thanks a lot!
Gergő
This is a bit tricky, but we can do it with the use of a temporary calculated summary table within a measure:
CountStatusB =
SUMX(
ADDCOLUMNS(
SUMMARIZE(
FILTER(
ALL(Inventory),
Inventory[TimeStamp] <= MAX(Inventory[TimeStamp])
),
Inventory[ID],
"LastTimeStamp",
MAX(Inventory[TimeStamp])
),
"Status",
LOOKUPVALUE(Inventory[Status],
Inventory[ID], Inventory[ID],
Inventory[TimeStamp], [LastTimeStamp])
),
IF([Status] = "B",
1,
0
)
)
First, we create a summary table which calculates the last TimeStamp for each ID value. To do this, we use the SUMMARIZE function on a filtered table where we only consider dates from the current day or earlier, group by ID, and calculated the max TimeStamp.
Once we have the maximum TimeStamp per ID for the current day, we can look up what the Status is on that day and add that as a column to the summary table.
Once we know the most recent Status for each ID for the current day, we just need to sum up the ones where that Status is "B" and ignore the other ones.
It may be easier to read the measure if we break it up into steps. Here's the same logic as before, but using variables for more clarity.
CountB =
VAR CurrDay = MAX(Inventory[TimeStamp])
VAR Summary = SUMMARIZE(
FILTER(
ALL(Inventory),
Inventory[TimeStamp] <= CurrDay
),
Inventory[ID],
"LastTimeStamp",
MAX(Inventory[TimeStamp])
)
VAR LookupStatus = ADDCOLUMNS(
Summary,
"Status",
LOOKUPVALUE(Inventory[Status],
Inventory[ID], Inventory[ID],
Inventory[TimeStamp], [LastTimeStamp]
)
)
RETURN SUMX(LookupStatus, IF([Status] = "B", 1, 0))

Calculate value if same customer

I have the following code to count days:
count_days:
DATEDIFF('day',LOOKUP(ATTR([visit_day]),-1),ATTR([visit_day])
and the outcome is the following:
customer_id | visit_day | count_days
customer 1 | 1/1/2016 |
customer 2 | 1/3/2016 | 2
customer 2 | 1/15/2016 | 12
customer 3 | 2/1/2016 | 16
customer 3 | 2/5/2016 | 4
I'm trying to write another function that fires the previous function only by customer, so the first day of one customer is not subtracted by the last day of the previous customer. The outcome should look like this:
customer_id | visit_day | count_days
customer 1 | 1/1/2016 |
customer 2 | 1/3/2016 |
customer 2 | 1/15/2016 | 12
customer 3 | 2/1/2016 |
customer 3 | 2/5/2016 | 4
I have tried this code so far:
IF ATTR([customer_id]) != ATTR([customer_id])
THEN
NULL
ELSE
[count_days]
END
Any thoughts about this code to make it work?
You are very close. You can alter your calculated field like so:
IF LOOKUP(ATTR([Customer Id]),-1) = ATTR([Customer Id]) THEN
DATEDIFF("day",LOOKUP(ATTR([Visit Day]),-1),ATTR([Visit Day]))
END
It will render this result: