In the below code I have two tables. I join these, perform a GROUP BY on “Spot” and then a MIN() on a value calculated via the join.
The problem is that I also wish to obtain the value of Column2 for my resultant rows. At the moment I cannot select this immediately because Column2 is not part of the GROUP BY and it is not part of an aggregate function.
Also, I cannot perform a 3rd JOIN on the data to get this column, because I will just end up going around in circles, as my join condition would be on DerivedValue and in order to get this I will need to produce another GROUP BY….. and I will go around in circles.
If it helps to understand- temp4 is just a table containing 1s and 0s, performing a mask (hence the MIN() is done on the multiplication of these two)…..
EDIT: Please note, the reason why I am joining the same table is because I am effectively subtracting two values from a matrix and it was the easiest way to get the correct values all in one row to subtract.
SELECT temp3.Column1, min(temp3.DerivedValue * Probability) FROM
(SELECT temp1.Spot AS Spot, temp1.Vol AS Vol, temp1.Value- temp2.Value AS DerivedValue FROM
(SELECT Spot, Vol, Value FROM My_Table_1) temp1
INNER JOIN
(SELECT Spot, Vol, Value FROM My_Table_1) temp2
ON temp1.Spot = temp2.Spot) temp3
JOIN
(SELECT Spot, Vol, Probability FROM My_Table_2) temp4
ON temp3.Spot = temp4.Spot AND temp3.Vol = temp4.Vol
GROUP BY temp3.Spot
You cant select a column not present in either in the GROUP BY clause or aggregation. The reason is that there is no way to compress values from multiple rows into one data cell. For example if you group 20 rows into one, how to decide which value to select into the result in this row? You should instruct the query to select the right value, either with grouping on it, or aggregating somehow.
Otherwise it can’t be done. Maybe consider to rephrase your question to get some workaround for your exact problem.