4
I have the following select:
SELECT A.CARRO,
(SELECT TOP 1 VALOR FROM tab2 B WHERE B.DATA <= A.DATA ORDER BY B.DATA DESC) VALOR
FROM tab1 A
In
(SELECT TOP 1 VALOR FROM tab2 B WHERE B.DATA <= A.DATA ORDER BY B.DATA DESC)will bring me theVALORconcerning thatDATAor the "most recent".
I tried to make, um GROUP BY for CARRO, various forms, one of them:
SELECT A.CARRO,
SUM((SELECT TOP 1 VALOR FROM tab2 B WHERE B.DATA <= A.DATA )) VALOR
FROM tab1 A
GROUP BY A.CARRO
But returns me error:
It is not possible to perform an aggregation function in an expression that contains an aggregate or a sub-consumption.
- You really can’t do the
GROUP BYif you have a subquery to bring value from the column? - It would be because of the "systemic sequence" that SQL works, or something like?
- What other ways could you do to get the result?
"no way to do GROUP BY if you have a subquery" unfortunately no. You would have to put everything in a temporary table for example in order to group. Think the
group byand the aggregation functions work "together" to produce the query result, but a subquery harms that– Ricardo Pontual
Why GROUP BY? The table
tab1has more than one line for the same value ofCARRO? // There is no correlation betweentab1andtab2by the columnCARRO?– José Diz
@Ricardopunctual Can I then create a view right!?... would be easier than temporary table
– rbz
@Josédiz yes, has several records, and no, unrelated. The relationship between them is still much worse than in this example !
– rbz
The solution would be to make a
JOINwith aSELECTwhere is the sum of the value grouped byCARRO, but there had to be a relationship between thetab1and thetab2.– João Martins
@Joãomartins Oh yes... but unfortunately it’s unrelated.
– rbz
And should I not? Otherwise how do you know which records in the table
tab1relate to those oftab2?– João Martins
@Joãomartins No. There is much more Jooin and select in the query. The ratio is minimal near the large period. Besides that there is no way, as it is a system that I can create tables in client layer only. 100% discarded.
– rbz