How to calculate gross margin in Postgresql with needing multiple formulas? - postgresql

I am still learning postgresql after my company converted from MySQL and running into an issue with this report I was asked to make, which I would like to show a single value as a percentage showing our gross margin.
I need to calculate our profit margin which would be invoices.total -earnings.amount -jobs.off_cost / invoices.total . With our data types, I have to divide anything currency by 100.
I'm also struggling to figure out the best way to do this, as for every job a field calculating the earnings.amount will populate and I cannot remove, but if a job has an "off cost" which is often very much more, it will count both amounts as having been spent, when in those cases it was only the "off cost" that was paid/spent.
This report is also being filtered by time ranges, states, and company names.
With the code I have below it is pulling a very off number than expected (in billions, which we definitely aren't making.)
I appreciate any and all help that can be provided!
SELECT SUM( (invoices.total) - (earnings.amount) - (jobs.off_app_server_cost) / (invoices.total) /100) as "Profit Margin"
FROM law_firms
LEFT JOIN jobs on law_firms.id = jobs.law_firm_id
LEFT JOIN invoices on law_firms.id = invoices.law_firm_id
LEFT JOIN states on jobs.state_id = states.id
LEFT JOIN earnings on jobs.id = earnings.job_id
WHERE invoices.deleted_at IS NULL
AND law_firms.deleted_at IS NULL
AND CAST(invoices.created_at AS DATE) BETWEEN {daterange.start} AND {daterange.end}
AND law_firms.id = {Law_Firm}
AND states.name = {State_Name}
AND invoices.total != 0.00
invoice total
earnings amount
off cost
margin
100
30
N/A
70
200
40
300
-70
300
50
400
-33

Related

How to query after a starsystem that cointains two planets with a mass higer than 10 times a standard mass

I am working on a task in order to learn PostgreSQL, and got stuck on a problem.
Given the two tables: a star-table and a planet-table. The star-table contains star systems, and the planet-table contains planets that are located within the star systems. In other words the planet-table references the star-table with the foreign key star.
My question is: How do you query for a planet name that is contained in a solar system with two planets with a mass greater than 10 standard masses, where the star has a distance less than 50 parsecs away from our sun? (The standard mass measurement in this specific task is a scale of Jupiter masses referenced as a whole number).
the tables look like this:
My best previous attempt goes likes this, and return 79 rows.
SELECT p.name, s.name FROM planet AS p
INNER JOIN star AS s
ON (s.name = p.star)
WHERE s.distance < 50 AND p.mass > 10; -- I don't know how to check for two planets with a mass greater than 10
The correct answer should return 4 rows.
All help is appreciated and much welcomed
Your query will do, but since you only want to query for the star system, the following may be closer to what you want:
SELECT s.name
FROM star AS s
WHERE s.distance < 50
AND EXISTS (SELECT 1 FROM planet AS p
WHERE s.name = p.star
AND p.mass > 10);

How do I apply a filter, but only to a part of a stacked bar in Tableau?

I have the following order data:
for every hour, the blue part shows the amount of invalid orders, while the orange part indicates valid orders. I have created a filter to filter orders with prices greater than 300 USD, but I want to apply the filter to valid orders only .I cannot figure out how to do that, I want each of the stacked bars to have three pieces: invalid orders, valid orders below 300 usd and valid orders above 300 usd.
An alternative would be to have three bars (total order amount, valid order count,valid and gretaer than 300 USD count) grouped for every hour, Which, once again, I cannot figure out how to do it. Please Help me out.
Clarification: original data looks like this
It's tough to answer properly when I can't see Rows, Columns and the Marks Card, but can create a calculated field that is something like:
if [Order Total] >= 300 then 1 end
and another
if [Order Total] < 300 then 1 end
and use both of these instead of your orange bar (is that COUNT(Order) ?) that you have now.

Aggregating MDX Cube Data of Survey results in Tableau

I’m a Tableau developer – but been asked to create a viz from and Cube using MDX (which I have no experience of).
The Cube is connected to Tableau, some Sets have been created for Time dimensions - Current Month etc – but totally lost trying to aggregate results so I can move on...
The Data I have is a simple survey with 3 questions. The responder (I responder per Form ID) can give 1 of 4 answers to each question – or ignore it.
2 sets have been created in Tableau to reflect these:
Set 1 Questions: Q1, Q2, Q3
Set 2 Answers: No, Maybe, Probably, Yes (and not answered/#NA)
So far, using ad CASE Statement in Tableau Calculated Members, I’ve assigned a value to each of these answers – No = 0, Maybe = 33, Probably = 67, Yes = 100 or #NA.
I’ve created 2 Calculated Members:
[Count of Answers] – so I can show volume of surveys answered:
IIF([Answer].[SAnswer].currentmember = [Yes], [Measures].[Number Of
Answers], (IIF([Answer].[SAnswer].currentmember = [Probably], [Measures].
[Number Of Answers], (IIF([Answer].[SAnswer].currentmember = [Maybe],
[Measures].[Number Of Answers], (IIF([Answer].[SAnswer].currentmember =
[No], [Measures].[Number Of Answers],0)))))))
And,
[Survery Scores]
CASE
WHEN [Answer].[SAnswer].currentmember = [Yes] THEN 1.00
WHEN [Answer].[SAnswer].currentmember = [Probably] THEN 0.67
WHEN [Answer].[SAnswer].currentmember = [Maybe] THEN 0.33
WHEN [Answer].[SAnswer].currentmember = [No] THEN 0.00
ELSE NULL
END
Where I’m stuck – For each survey form completed, I need the average score:
[Form ID].[001], has 3 questions answered: Q1 = 67%, Q2 = 67%, Q3 = 67% so average is 67%
[Form ID].[002], has 2 questions answered: Q1 = 100%, Q3 = 0% so average is 50%
I’ll need to aggregate these Scored by Country, Region, Job Type, Month hierarchies etc…if I was just using an flat extract I’d use a Nested Include/Fixed LOD…so if the 2 forms above were in the same [June].[USA].[Cleaning] the score would be average of 58.5%.
I'd appreciate a steer on what I need to do to create an aggregated score measure averaging the average score-per-form at any level. Many thanks in advance.
Your problem is related more to your Cube design then MDX. The average method that you explained above indicates that the grain of your fact is your form . I would suggest that you edit the design of your fact, by grouping on the fact on formid. Now at what ever data point you query the data the result will be fine.

Calculating Running Balances

I am struggling with how to calculate a running balance that is dynamic. Here's what I have.
A range of periods with an intersection between total duration and each month in the duration.
A rate that is applied at each intersection.
An initial amount
A need to calculate a running balance based on the initial amount less the rate applied in that period.
For example, I have a project worth $2,500,000 that is 8 months long. The rates for each interval are as follows: 1. 8.10% 2. 14.04% 3. 26.8% 4. 29.1% 5. 33.4% 6. 30.4% 7. 47.4% 8. 100%
For period 1 I have $202,500 (8.10% × $2.5 million), For period 2, I have $322,500 (14.04% × $2,297,500 ($2.5 - $202,500)), for period 3, I have $530,000 (26.8% × $1,974,999 ($2.5 - sum of first two periods ($525,000)). At the end of period 8, my balance is $0 and my earned amount = $2.5 million.
Can I use something like RunningTotal = Sum(MonthlyAmts) OVER (ORDER BY XX ROWS UNBOUNDED PRECEDING), ORDER BY Period? Or is this a candidate for a cursor?
Thanks in advance!
It depends on your table structure. But it sounds like you should use function. If you would like get all years use table valued function, if you are interested only on result use scalar function. Or better way with recursive CTE.

Running total quick calculation in Tableau with two different groupings

I have the following chart, which uses Quick Table calculation to count the percentage of the values across the group Category for each month.
What I want is to count the percentage of the monthly running total of the values across the group Category for each month. I can create the quick calculation for monthly running total, separately, but I can't seem to combine it with this below because one requires quick calculation across the table and another across the group. Can anyone advise if this is doable?
The workbook attached here, with the problem above in the second tab.
Edit: Let me give example what I meant here:
April: A = 1000, B=500, C= 200, D=300 -> total is 2000
percentage in April in chart is A = 1000/2000 = 50%, B = 25%, C = 10%, D = 15%, total = 100%
May: A=2000, B=2000, C=1800, D=200 ->
cumulative April+May A=3000, B=2500, C=2000, D=500 -> total is 8000
percentage in May in chart is A=3000/8000 = 37.5%, B = 31.25%, C = 25%, D = 6.25%, total = 100%
I got an answer elsewhere and thought I should update here. The solution was to use a secondary table calculation. Basically, after putting SUM(Value) pill in Row:
right click on it to select Add Table Calculation
set as primary calculation the Running Total Sum of Table (Across)
check the box to Perform a secondary calculation on the result
set as secondary calculation the Percent of Total of Table (Down)
See below screenshot of the setting.
Are you looking for ways to calculate the sum of the running total across the category? it is not clear when you say to count the percentage? However if you are looking for sum of percentage running total across your category... you can edit your calculation and set the calculation type as running total, the summarize value ( you can choose, sum , average, min,...max) and the running along option choose category.