I have created this working statement for calculating "C" by using the formula C=A/B*1000000.
This works as expected and the C column is calculated correctly:
Select chemicals.Region As Region,
chemicals.Totalt As `A`,
`area`.`m2` As `B`,
((chemicals.Totalt / `area`.`m2`) * 1000000) As C
From (chemicals Join `area` On chemicals.branch = `area`.branch)
Now I need to use the same formula in an aggregated report, so I tried this:
Select chemicals.Region As Region,
sum(chemicals.Totalt) As `A`,
sum(`area`.`m2`) As `B`,
sum( ((chemicals.Totalt / `area`.`m2`) * 1000000)) As C
From (chemicals Join `area` On chemicals.branch = `area`.branch) GROUP BY Region
But then the value of "C" is not calculated correctly.
I am sure there is a way to get this right, but simply adding a sum sum function to the "C" calculation was not correct. (The columns A and B are correct, by the way).
Thanks for all help!
As figured out in the comments, the following solution will work:
((sum(chemicals.TotalT) / sum(area.m2)) * 1000000) as C
Related
I have a query with columns "Cremembers.Name" (this pulls the "Name" column from the table "Crewmembers") and "Sum of HoursUW" (this sums "HoursUW" from a different table "Marine391" per "Crewmember.Name". There is an existing relationship between Cremembers.Name and Marine391.Crewmembers where all Cremembers.Name values are listed and only values from Marine391.Crewmembers are listed where the joined fields are equal.
In this query, if a crewmember does not have any HoursUW, I want the default value of "Sum of HoursUW" to be 0.
This is the current SQL code:
SELECT DISTINCTROW Crewmembers.Name, Sum(Marine391_29ft_SAFEBOAT.HoursUW) AS [Sum Of HoursUW]
FROM Crewmembers LEFT JOIN Marine391_29ft_SAFEBOAT ON Crewmembers.[Name] = Marine391_29ft_SAFEBOAT.[Crewmembers].[Value]
GROUP BY Crewmembers.Name;
I tried using the nz() function like this:
nz((SELECT DISTINCTROW Crewmembers.Name, Sum(Marine391_29ft_SAFEBOAT.HoursUW), 0) AS [Sum Of HoursUW]
FROM Crewmembers LEFT JOIN Marine391_29ft_SAFEBOAT ON Crewmembers.[Name] = Marine391_29ft_SAFEBOAT.[Crewmembers].[Value]
GROUP BY Crewmembers.Name;
and like this:
SELECT DISTINCTROW Crewmembers.Name, nz(Sum(Marine391_29ft_SAFEBOAT.HoursUW), 0) AS [Sum Of HoursUW]
FROM Crewmembers LEFT JOIN Marine391_29ft_SAFEBOAT ON Crewmembers.[Name] = Marine391_29ft_SAFEBOAT.[Crewmembers].[Value]
GROUP BY Crewmembers.Name;
These both had syntax errors.
How can I use the nz() function or is there a better way to set the default value to 0 in this query?
Thanks in advance!!!
Apply Nz() directly to the HoursUW field as you Sum() it.
SELECT cm.Name, Sum(Nz(msb.HoursUW, 0)) AS [Sum Of HoursUW]
FROM
Crewmembers AS cm
LEFT JOIN Marine391_29ft_SAFEBOAT AS msb
ON cm.[Name] = msb.[Crewmembers].[Value]
GROUP BY cm.Name;
I did not include DISTINCTROW because the query's result set rows will already be distinct by virtue of the GROUP By.
I plan to make two with queries that make two temporary tables, one which gives the sum of the remaining loan payments, and one that gives the sum of all the transactions in the table. I've tested the two with statements and they work by themselves, however trying to perform a select query with them only seems to return errors.
WITH RemainingLoans AS(SELECT SUM(TIMESTAMPDIFF(MONTH, l.NextPayment, l.FullPaymentConfirmed) * l.MonthlyPaymentRate) AS RemainingPayments FROM loans AS l);
WITH CurrentBalances AS(SELECT SUM(t.amount) AS allBalances FROM transactions AS t);
SELECT l.RemainingPayments - b.allBalances AS TotalOutstandings FROM RemainingLoans AS l, CurrentBalances AS b;
The first with is called RemainingLoans with one attribute RemainingPayments, and the second with is called CurrentBalances with one attribute allBalances. To my knowledge these should work like tables which is why I attempted my select clause on the third line, however I am currently getting syntax errors. Is there a correct way to format my select statement?
This should be a single statement, not multiple statements.
The fiddle
WITH list elements are separated by a comma. There's only one WITH keyword at the beginning of the list.
The semicolon goes at the end of the entire statement, not after the WITH list elements.
Here's the adjusted statement:
WITH RemainingLoans AS (
SELECT SUM(TIMESTAMPDIFF(MONTH, l.NextPayment, l.FullPaymentConfirmed) * l.MonthlyPaymentRate) AS RemainingPayments
FROM loans AS l
)
, CurrentBalances AS (
SELECT SUM(t.amount) AS allBalances
FROM transactions AS t
)
SELECT l.RemainingPayments - b.allBalances AS TotalOutstandings
FROM RemainingLoans AS l
, CurrentBalances AS b
;
I'm new to SQL.
Problem: Say if I were to count the amount that is contained in the alias table of "x" COUNT(x.xValue) to be 217. Now when I add the sub-query "y" and then do the count again, I have the COUNT(x.xValue) to suddenly square its self -> 47089. Why is this happening?
(Note: Both alias tables "x" and "y" have the same amount -> 217.)
How do I fix this problem. I don't want to use Variables or Views.
SELECT COUNT(x.xValue) + COUNT(y.yValue) AS CountXY
FROM
(SELECT value AS xValue FROM table1
WHERE
...) AS x,
(SELECT value AS yValue FROM table1
WHERE
...) AS y
Result of 'CountXY' : 94178.
Result I'm expecting 'CountXY' : 434
The problem is that you are doing two sub-queries and then trying to call the values return directly.
This will behave as selecting one value from table x and matching it to every single value in table y. This obviously creates the squared return effect.
What you need to use is the JOIN to combine both data-sets so that you get the 1 to 1 relationship you are trying to achieve.
This is how the above should be done with your previous sub-query:
SELECT COUNT(A.value) AS x, COUNT(B.value) AS y
FROM table1 AS A
JOIN table1 AS B
ON A.attr1 = B.attr1
AND A.attr2 = B.attr2
WHERE B.attr1 != 'whatever'
AND B.attr2 = 'whatever'
AND A.attr3 = 'something'
AND B.attr3 = 'something different'
The above query should return the correct 1 to 1 relationship you are looking for. Replacing your sub-query with the one above should give you the correct answer
I'm trying to figure how to calculate the pearson correlation coefficient using sql. Here is the formula I'm using:
and here is the table I'm using:
This is what I have so far for a query but it's giving me this message: Invalid use of group function
select first_id, second_id, movie_id, first_score, second_score, count(*) as n,
sum((first_score-avg(first_score))*(second_score-avg(second_score)))/
(
sqrt(sum(first_score-avg(first_score)))*
sqrt(sum(second_score-avg(second_score))))
as pearson
from connections
group by second_id
Thanks for helping
Here is a query that does the calculation in the formula:
select sum((first_score - avg_first_score)*(second_score - avg_second_score)) /
(sqrt(sum(pow((first_score - avg_first_score), 2)))*
sqrt(sum(pow((second_score - avg_second_score), 2)))
) as r
from connections c cross join
(select avg(first_score) as avg_first_score, avg(second_score) as avg_second_score
from connections
) const;
There are numerous issues with your attempt. This precalculates the average values for the two scores. It then applies the formula pretty much as written.
From a purely syntactic perspective, you've got a problem with your group by clause. It should list every non-aggregated column to work properly. It should be:
group by first_id, second_id, movie_id, first_score, second_score
What I'm attempting to do find values in a table which are less than the MAX of another field, minus a numeric value. Eg:
...WHERE some_table.value_1 = 0 AND another_table.value_2 <= (SELECT MAX(another_table.value_3) - 5) ORDER BY...
However, this is not working! My joins are all fine, and the query runs without the 2nd part of the WHERE statement, but if you'd like to see the rest of the code for more info, let me know!
Cheers!
Sparkles*
ps all the values are integers
Here is a working example using joins, try to apply it to yours:
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t1.join_field = t2.join_field
WHERE t1.some_field = 1
AND t2.other_field <= (
SELECT (MAX(t22.third_field) - 5)
FROM table2 t22
);
If this is not exactly what you were looking for, please let me know and I will update it.
Use HAVING MAX(...)
Something like:
SELECT MIN(p.price) AS price, p.pricegroup
FROM articles_prices AS p
_YOUR_JOINED_TABLE_
WHERE p.articleID=10
GROUP BY p.pricegroup
HAVING MAX(p.price) > _VALUE_FROM_JOINED_TABLE_;