SQL updates to table using WINDOW-like function in WHERE clause - sql-update

I have a report that summarizes sales deals by rep, account, deal number, and a flag if they have been contacted by HQ to see if they need additional help. As I extract the data, I can see that some sales reps have multiple deals in progress at the same account.
Here's a sample of the report. In this sample, Sales rep A has been contacted but Sales rep B has never been contacted. We want to fill in the Sales rep A contacted fields while leaving Sales rep B as
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Sales rep A | 1
Sales rep A | account 2 | <null> | 2
Sales rep A | account 1 | <null> | 3
Sales rep B | account a | <null> | 1
Sales rep B | account b | <null> | 2
...
I want to update the contacted column with either 'Sales rep A' (or 'YES')
so that it looks like this:
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Yes | 1
Sales rep A | account 2 | Yes | 2
Sales rep A | account 1 | Yes | 3
Sales rep B | account a | <null> | 1
Sales rep B | account b | <null> | 2
...
This looks like a case for a window function to me, but maybe a self-join would be better. I tried to work out what the select function would look like
SELECT "opportunity owner", "contacted", "Account", "deal no."
DENSE_RANK () OVER (PARTITION by
--"opportunity owner"
(SELECT "opportunity owner" FROM "test_weekly_top_deal_report" WHERE "worked with this rep before?" LIKE 'Sales rep A')) AS "rank"
FROM "test_weekly_top_deal_report"
WHERE "opportunity owner" LIKE 'Sales rep A'
Which gives me:
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Sales rep A | 1
Sales rep A | account 2 | <null> | 2
Sales rep A | account 1 | <null> | 3
But when I modified it to run over all the reps, I used this:
SELECT "opportunity owner", "worked with this rep before?", "account name",
DENSE_RANK () OVER (PARTITION by
--"opportunity owner"
(SELECT "opportunity owner" FROM "test_weekly_top_deal_report" WHERE "worked with this rep before?" NOT LIKE 'NO')) AS "rank"
FROM "test_weekly_top_deal_report"
With just the small change in the WHERE clause now reading "NOT LIKE 'NO' ". That just gave me an error:
The database reported a syntax error: [Amazon](500310) Invalid operation:
Invalid Query: Details: ----------------------------------------------- error:
Invalid Query: code: 8001 context: single-row subquery returns more than one row query: 2151115 location: 0.cpp:8
Suggestions? How do I make this iterate over all the reps and thus fill in the column "contacted"?

select ("opportunity owner" from "test_weekly_top_deal_report"
where "contacted" is "opportunity owner") as X;
select case
when ("opportunity owner" in (X)) and ("contacted" is null or "contacted" is "opportunity owner")
then 'Yes'
else 'No' as contacted
from "test_weekly_top_deal_report"

Related

Calculate monthly balance in PowerBI

Data-Table:
DB-Fiddle
CREATE TABLE vouchers (
id SERIAL PRIMARY KEY,
event_date DATE,
credits_collected INT,
credits_redeemed INT
);
INSERT INTO vouchers
(event_date, credits_collected, credits_redeemed
)
VALUES
('2020-01-08', '900', '700'),
('2020-02-15', '500', '300'),
('2020-02-20', '100', '250'),
('2020-03-19', '600', '850'),
('2020-04-03', '450', '130');
SQL-Query:
SELECT
t1.event_month AS event_month,
t1.credits_collected AS credits_collected,
t1.credits_redeemed AS credits_redeemed,
SUM(t1.credits_collected - t1.credits_redeemed) OVER (
ORDER BY t1.event_month ASC ROWS UNBOUNDED PRECEDING) AS balance
FROM
(SELECT
DATE_PART('month', v.event_date) AS event_month,
SUM(v.credits_collected) AS credits_collected,
SUM(v.credits_redeemed) AS credits_redeemed
FROM vouchers v
GROUP BY 1
ORDER BY 1) t1
GROUP BY 1,2,3
ORDER BY 1;
Result:
event_month | credits_collected | credits_redeemed | balance
-------------|---------------------|--------------------|------------
1 | 900 | 700 | 200
2 | 600 | 550 | 250
3 | 600 | 850 | 0
4 | 450 | 130 | 320
I am loading the above data-table into PowerBI.
Now, I want to create a report that looks like the results I am getting with the SQL-Query above.
I am able to put credits_collected and credits_redeemed to the report.
However, I have no clue what DAX formula I need to calculated the balance for the end of each month.
Do you have any idea how I can solve this issue?
I could solve the issue with two steps:
Step 1: Implementing an additional column with this DAX formula:
column_balance_calculated_daily = CALCULATE(SUM(Tabelle1[credits_collected])-SUM(Tabelle1[credits_redeemed]),ALL('Tabelle1'),'Tabelle1'[event_date]<=EARLIER('Tabelle1'[event_date] ))
Step 2: Use the column in the following DAX formula:
balance = CALCULATE(MAX(Tabelle1[column_balance_calculated_daily]),ENDOFMONTH(Tabelle1[event_date]))

Power BI - Cannot figure out DAX logic to show dynamic last 6 months data as a tooltip

I have a finance PowerBI report that I'm trying to enhance, but struggling on this particular tooltip. Hopefully someone more knowledgable than me can help me out :)
Ok here's the relevant data model setup:
Table Name: "Date"
| Date | Month Year |
|:----------- |:------------:|
| 01/01/2022 | January 2022 |
| 02/01/2022 | January 2022 |
| 03/01/2022 | January 2022 |
etc.
Table Name: "Categories"
| Category |
|:------------------- |
| Household Shopping |
| Bills |
| Mortgage / Rent |
| Motoring |
| Payslip |
| Income |
etc.
Table Name: "Transactions"
| Date | Transaction | Category | Amount |
|:----------- |:-----------------|:-------------------|:-------|
| 05/01/2022 | Mortgage Payment | Mortgage / Rent | -£1000 |
| 05/01/2022 | Electricity Bill | Bills | -£80 |
| 08/01/2022 | Salary | Payslip | £2500 |
| 11/01/2022 | Grocery Shopping | Household Shopping | -£45 |
| 12/01/2022 | DIY Store | Household Shopping | -£170 |
| 12/01/2022 | Car Fuel | Motoring | -£80 |
etc.
And the model is Date --> Transactions <-- Category
I have a report that shows a snapshot of my finances and spending on a monthly basis, so there's a dropdown slicer at the top of the page where I can change the month (Date[Month Year]) and all the visuals update to show relevant data for that particular month.
I have these measures to calculate my earnings and spending:
Earnings =
CALCULATE (
SUM ( Transactions[Amount] ),
OR ( Transactions[Category] = "Payslip", Transactions[Category] = "Income" )
)
Spending =
( -1 )
* CALCULATE (
SUM ( Transactions[Amount] ),
Transactions[Category] <> "Payslip",
Transactions[Category] <> "Income"
)
Spending % of Earnings =
DIVIDE ( [Spending], CALCULATE ( [Earnings], ALL ( Categories ) ) )
On this page I have 2 bar charts that shows my spending for each category. These both have the y-axis as Categories[Category] and the value as the "Spending" and "Spending & of Earnings" measures respectively.
So far all works well.
Here's where I'm getting stuck. When I hover over the various bars, I would like to see a tooltip that shows a column/line chart of those measures over the past 6 months. For example if I selected June 2022 in the page slicer, I'd like the tooltip to show the spending measures for Jan 2022 - June 2022.
I've managed to get a tooltip that shows data for the past 6 months, and think it works for the 'Spending' measure. But for the life of me I can't get the 'Spending % of Earnings' working. I assume there's some combination of DAX to do it but I'm struggling.
Could someone please help me with this?

ALL() isn't working to "remove a filter" in DAX; relationship issue?

Basic premise:
'Orders' are comprised of items from multiple 'Zones'.
Customers can call in for 'Credits' (refunds) on botched 'Orders'.
There is a true many-to-many relationship here, because one order could have multiple credits called in at different times; similarly, a customer can call in once regarding multiple orders (generating only one credit memo).
'Credits' granularity is at the item level, i.e.
CREDIT | SO | ITEM | ZONE | CREDAMT
-------------------------------------------------------
42 | 1 | 56 | A | $6
42 | 1 | 52 | A | $8
42 | 1 | 62 | B | $20
42 | 2 | 56 | A | $12
'Order Details' granularity is at the zone level, i.e.
SO | ZONE | DOL_AMT
-------------------------------
1 | A | $50
1 | B | $20
1 | C | $100
2 | A | $26
I have a 'Zone' filter table that helps me sort things better and roll up into broader categories, i.e.
ZONE | TEMP | SORT
-------------------------------
A | DRY | 2
B | COLD | 3
C | DRY | 1
What I need:
I want a pair of visuals for a side by side comparison of order total by zone next to credit total by zone.
What's working:
The 'Credits' component is easy, CreditTotal = abs(sumx(Credits,Credits[CREDAMT])) with Zone as a legend item.
I have a ORDER component that works when the zone is in the credit memo
Order $ by Zone =
CALCULATE (
SUM ( 'Order Details'[DOL_AMT] ),
USERELATIONSHIP ( 'Order Details'[SO], Credits[SO] ),
ALL ( Credits[CreditCategory] )
)
My issue:
Zones that didn't have a credit against them won't show up. So instead of
CREDIT | ZONE | ORDER $ BY ZONE
----------------------------------
42 | A | $76
42 | B | $20
42 | C | $100
I get
CREDIT | ZONE | ORDER $ BY ZONE
----------------------------------
42 | A | $76
42 | B | $20
I have tried to remove this filter by tacking on ALL(Zones[Zone]) and/or ALL('Order Details'[Zone]), but it doesn't help, presumably because it is reporting "all zones" actually found in the 'Credits' table. I'm hoping there's some way to ask it to report all zones in the 'Order Details' table based upon SOs in the 'Credits' table.
In case it helps, here's how the relationships are structured; as an aside, I've tried mixing and matching various combinations of active/inactive, single vs. bidirectional filtering, etc., but the current configuration is the only one that seems to remotely work as desired.
I'm grateful for any suggestions; please let me know if anything is unclear. Thank you.
I was able to get it to work by using 'Order Details'[Zone] rather than Zones[Zone] in the table visual and this measure:
Order $ by Zone =
CALCULATE (
SUM ( 'Order Details'[DOL_AMT] ),
USERELATIONSHIP ( 'Order Details'[SO], Credits[SO] )
)
Notice that regardless of your measure, there is no row in Credits corresponding to zone C, so it doesn't know what to put in the CREDIT column unless you tell it exactly how.
If you remove the CREDIT dimension column, then you don't need to swap tables as I suggested above. You can just use the measure above and then write a new measure for the CREDIT column instead:
CreditValue =
CALCULATE(
VALUES(Credits[CREDIT]),
ALL(Credits),
Credits[SO] IN VALUES('Order Details'[SO])
)

Total/Sum working incorrectly in Power Bi

I have created a Report in which I have created some measures like -
X =
CALCULATE (
DISTINCTCOUNT ( ActivityNew[Name] ),
FILTER (
ActivityNew,
ActivityNew[Resource Owner Name] = MAX ( 'Resource Owners'[Manager Name] )
&& ActivityNew[LocationId] = 2
)
)
When I use this measure in table then the column values dont add up. For eg. if the value of this measure is 2,2,2,2,2 then Total in table should be 10. but it is showing 2.
I have noticed that wherever I have used this MAX(), the measure values are not adding up.
Why this is happening and Is their any solution for this?
You are using DISTINCTCOUNT which is in general not aggregatable.
Say you have the following table Sales:
+----------+------+-------+
| Customer | Item | Count |
+----------+------+-------+
| Albert | Coke | 3 |
| Bertram | Beer | 5 |
| Bertram | Coke | 2 |
| Charlie | Beer | 1 |
+----------+------+-------+
If you wanted to count the number of distinct items each customer has bought, you would create a new measure with the formula:
[Distinct Items] := DISTINCTCOUNT(Sales[Item])
If you include the [Customer] column and your [Distinct Items] measure in a report, it would output the following:
+----------+----------------+
| Customer | Distinct Items |
+----------+----------------+
| Albert | 1 |
| Bertram | 2 |
| Charlie | 1 |
+----------+----------------+
| Total | 2 |
+----------+----------------+
As you can see, this does not sum up, as the context of the total row, is the entire table, not filtered by any particular customer. To change this behaviour, you have to explicitly tell your measure that it should sum the values derived at the customer level. To do this, use the SUMX function. In my example, the measure formula should be changed like this:
[Distinct Items] := SUMX(VALUES(Sales[Customer]), DISTINCTCOUNT(Sales[Item]))
As I only want to sum over unique customers I use VALUES(Sales[Customer]). If you want to sum over every row in the table simply do: SUMX(<table name>, <expression>).
With this change, the output in the above example would be:
+----------+----------------+
| Customer | Distinct Items |
+----------+----------------+
| Albert | 1 |
| Bertram | 2 |
| Charlie | 1 |
+----------+----------------+
| Total | 4 |
+----------+----------------+

Expected known function, got 'count',how can I use count in doctorine?

I have table like this
reviews in restaurant table are tied as foreign key with reviews table
Restaurant table
ID| name | reviews
1 | subway | 1,2
2 | macdonald | 3
Review table
ID| review
1 | review about subway1
2 | review about subway2
3 | review about macdonald
Normally I can fetch Resturant data as
$query = $this->em->createQuery(
"SELECT a FROM Restaurant a);
However I would like to order the number of review column.
Now I made sentence like this but in vain.
$query = $this->em->createQuery(
"SELECT a FROM Restaurant a
INNER JOIN Review r
order by count(a.reviews) ");
it shows error like this.
Expected known function, got 'count'
You should have the restaurant ID in the reviews table, so that you skip the complications of having a comma-separated string in the restaurant table.
Restaurant table
ID| name
1 | subway
2 | macdonald
Review table
ID| restaurant ID | review
1 | 1 | review about subway1
2 | 1 | review about subway2
3 | 2 | review about macdonald
Then you can do this:
$query = $this->em->createQuery(
"SELECT a, count(a.reviews) count1 FROM Restaurant a
INNER JOIN Review r
order by count1 ");